Flyweight
When you have
Instead of capturing the non-unique data per object, present a palette of
options for Clients to call upon as necessary. The
In graphical rendering, triangle mesh objects or sprites count as ConcreteFlyweight objects because you refer to them rather than holding a full mesh or sprite in each Client. In some documents, fonts, images such as logos, and even repeated composites can be shared in this manner—house planning software often uses a palette of doors, windows, and furniture items.
One way of thinking about the
The pattern is only practical when:
- You have a collection of objects
- Those objects have internal state
- Those objects have costly attributes in common
Without many objects, there cannot be attributes in common. Without the state, there is no call for unique Client objects. If they aren’t unique, you could reference the ConcreteFlyweight directly.
Client objects are stateful, while the ConcreteFlyweight objects are stateless.
You might also think of them as
If your composite does not require parents, you can use a ConcreteFlyweight as a leaf in your hierarchy, reducing costs.
“I have a house. Although, yes, I share it with quite a few others.”