Flyweight Pattern
Overview
Use sharing to support large numbers of fine-grained objects efficiently.
Participants
- declares an interface through which flyweights can receive and act on extrinsic state.
- implements the Flyweight interface and adds storage for intrinsic state,
if any. A ConcreteFlyweight object must be shareable. Any state it stores
must be intrinsic; that is, it must be independent of the ConcreteFlyweight
object's context.
- not all Flyweight subclasses need to be shared. The Flyweight interface
enables sharing; it doesn't enforce it. It is common for UnsharedConcreteFlyweight
objects to have ConcreteFlyweight objects as children at some level in the
flyweight object structure.
- creates and manages flyweight objects.
- ensures that flyweights are shared properly. When a client requests a flyweight, the
FlyweightFactory object supplies an existing instance or creates one, if none exists.
- maintains a reference to flyweight(s).
- computes or stores the extrinsic state of flyweight(s).
- is not automatically generated.
Parameters
-
when selected, will create special JavaDoc links in the code between pattern participants, describing
their relationships.
Applicability
The Flyweight pattern's effectiveness depends heavily on how and where it is used.
Apply the Flyweight pattern 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 states 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.