Java Reference
In-Depth Information
Not all Flyweights have to be shared, nor do the implementing classes need to be shared. This pattern allows object sharing, but does not
require it.
Use Flyweight only when it's easy to identify and extract the external data from the objects, and when the number of different states is
limited.
Implementation
The Flyweight class diagram is shown in Figure 3.8 .
Figure 3.8. Flyweight class diagram
To implement the Flyweight you need:
Flyweight - The interface defines the methods clients can use to pass external state into the flyweight objects.
ConcreteFlyweight - This implements the Flyweight interface, and implements the ability to store internal
data. The internal data has to be representative for all the instances where you need the Flyweight .
FlyweightFactory (see “ Abstract Factory ” on page 6) - This factory is responsible for creating and managing
the Flyweights . Providing access to Flyweight creation through the factory ensures proper sharing. The factory
can create all the flyweights at the start of the application, or wait until they are needed.
Client (page 183) - The client is responsible for creating and providing the context for the flyweights. The only
way to get a reference to a flyweight is through FlyweightFactory .
Benefits and Drawbacks
The obvious benefit of this pattern is the reduced number of objects to handle. This can save a lot of space, both
in memory and on storage devices, if the objects are persisted.
The most space will be saved when the context information for the flyweight is computed instead of stored.
However, this also leads to the drawback of this pattern: runtime costs.
Instead of storing many objects, clients now have to calculate the context and provide this to the flyweight. The
flyweight then uses this information to compute/provide functions. Handling fewer objects should increase
runtime performance if implemented correctly. Note that if the context information is small, and the flyweight is
large, the savings will be significant.
Pattern Variants
None.
Related Patterns
Related patterns include the following:
Abstract Factory (page 6) - The Abstract Factory pattern is used to provide access to flyweights so that these
factories ensure proper sharing of the Flyweight instances.
Composite (page 157) - The Composite is often used to provide structure.
State (page 104) - The State pattern is often implemented using the Flyweight pattern.
 
Search WWH ::




Custom Search