Applied Design Patterns with Java
Structural :: Flyweight (195) {C ch 14}
Implementation
Here are implementation issues to consider when using the
Flyweight pattern:
- Removing extrinsic state. The pattern's applicability is determined by how easy it is to identify extrinsic state
and remove it from shared objects. Removing extrinsic state won't help reduce storage costs if there are as many
different kinds of extrinsic state as there are objects before sharing. Ideally, extrinsic state can be computed
from a separate object structure, one with far smaller storage requirements.
- Managing shared objects. Because objects are shared, clients shouldn't instantiate them directly. FlyweightFactory
lets clients locate a particular Flyweight. FlyweightFactory objects often use an associative store to let
clients look up Flyweights of interest. Sharability also implies some form of reference counting or
garbage collection to reclaim a Flyweight's storage when it's no longer needed. However, neither is necessary
if the number of Flyweights is fixed and small (e.g., flyweights for the ASCII character set). In that
case, the Flyweights are worth keeping around permanently.
Related Patterns
The Flyweight pattern is often combined with the Composite
(163) pattern to implement a logically hierarchical
structure in terms of a directed-acyclic graph (DAG) with shared leaf nodes.
It's often best to implement State (305) and Strategy
(315) objects as Flyweights.
Catalog Structural Prev Next