Applied Design Patterns with Java
Structural :: Flyweight (195) {C ch 14}
Collaborations
- State that a Flyweight needs to function
must be characterized as either intrinsic or extrinsic. Intrinsic state is stored in the ConcreteFlyweight object;
extrinsic state is stored or computed by Client objects. Clients pass this state to the Flyweight
when they invoke its operations.
- Clients should not instantiate ConcreteFlyweights directly. Clients
must obtain ConcreteFlyweight objects exclusively from the FlyweightFactory object to ensure they are shared properly.
Consequences
The Flyweight pattern has the following 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. Such costs are offset by space savings,
which increase as more Flyweights are shared.
- Storage savings are a function of several factors: the
reduction in the total number of instances that comes from sharing, the amount of intrinsic state per object, whether
extrinsic state is computed or stored.
- The more Flyweights are shared, the greater the storage savings. The savings increase
with the amount of shared state. The greatest savings occur when the objects use substantial quantities of both
intrinsic and extrinsic state, and the extrinsic state can be computed rather than stored. Storage savings exists
in two ways: Sharing reduces the cost of intrinsic state, and there is a trade-off between extrinsic state for
computation time.
- The Flyweight pattern is often combined with the Composite
(163) pattern to represent a hierarchical structure as a graph
with shared leaf nodes. A consequence of sharing is that Flyweight leaf nodes cannot store a pointer to their parent. Rather, the parent pointer
is passed to the Flyweight as part of its extrinsic state. This impacts how the objects in the hierarchy communicate
with each other.
Catalog Structural Prev Next