Pattern: Flyweight

Synopsis

The Flyweight pattern is used when a fine-grained level of object detail is desired, but providing that detail literally would be prohibitively expensive.

Context

Specific Example: Telephone service. When a user picks up the receiver they're presented with a dial tone. This could potentially be modeled by having a tone-generator class servicing the request for the tone. Each phone line that is picked up will need to have a tone generated eventually. This could potentially be modeled as one generator per phone line. This would be prohibitively expensive on many resources, and also very inefficient. Instead what would be used is a pool of resources, in this case tone-generators, which is called upon when one is needed. User picks up the phone, one tone-generator is called from the available pool and services the user. When done the tone-generator is returned to the available pool.

General context: The resources which are needed can not be modeled literally because it would present too much of a drain on resources and would be inefficient.

Forces

There are several forces that affect that Flyweight:

Solution

Create a flyweight factory to handle flyweight management and possibly creation. The flyweight class defines the interface used by the flyweights to act on their state. The difference between the unshared concrete flyweight and the concrete flyweight is that not all of the flyweight classes need to be shared in this setup. The concrete flyweights may be children of unshared concrete flyweight classes.

Consequences

Implementation

Sample code

Related Patterns









Sources