Flyweight
14 Mar 2022Intent
Use sharing to support large numbers of fine-grained objects efficiently.
Applicability
The flyweight pattern's effectiveness depends heavily on how and where it's used. Apply flyweight when all of the following are true:
- An application uses a large number of objects.
- Storage costs are high because of the sheer quantity of objects.
- Most object state can be made extrinsic.
- Many groups of objects may be replaced by relatively few shared objects once extrinsic state is removed.
- The application doesn't depend on object identity. Since flyweight objects may be shared, identity tests will return true for conceptually distinct objects.
Structure
Participants
- Flyweight: declares an interface through which flyweights can receive and act on extrinsic state.
- ConcreteFlyweight: implements the flyweight interface and adds storage for intrinsic state, if any.
- UnsharedConcreteFlyweight: not all Flyweight subclasses need to be shared, the flyweight enables sharing, it doesn't enforce it.
- FlyweightFactory: creates and manages flyweight objects, ensures that flyweights are shared properly.
- Client: maintains a reference to flyweights, computes or stores extrinsic state of flyweights.
Collaborations
- State that a flyweight needs to function must be characterized as either intrinsic or extrinsic. Intrinsic is stored in ConcreteFlyweight object, extrinsic is stored by Clients.
- Clients should not instantiate ConcreteFlyweights directly, clients must obtain ConcreteFlyWeight objects exclusively from FlyWeightFactory object to ensure they are shared properly.
Consequences
Flyweights may introduce run-time costs associated with transferring, finding, and/or computing extrinsic state, especially if it was formerly stored as intrinsic state. However such costs are offset by space savings.
Sample Code
Related Patterns
- Flyweight pattern is often combined with the Composite pattern to implement a logically hierarchical structure in terms of a direct-acyclic graph with shared leaf nodes.
- It's often best to implements State and Strategy objects as flyweights.