The Flyweight pattern reduces the number of low-level, detailed objects within a system by sharing objects.
If instances of a class that contain the same information can be used interchangeably, the Flyweight pattern allows a program to avoid the expense of multiple instances
that contain the same information by sharing one instance. The figure below illustrates the Flyweight pattern.
The Flyweight pattern defines a structure for sharing objects.
Objects are shared for at least two reasons: 1) efficiency and 2) consistency.
The Flyweight pattern focuses on sharing for space efficiency.
Applications that use lots of objects must pay careful attention to the cost of each object. Substantial savings can be achieved by sharing objects instead of replicating them.
But objects can be shared only if they do not define context-dependent state.
Flyweight objects have no such state. Any additional information they need to perform their task is passed to them when needed.
Because they have no context-dependent state, Flyweight objects may be shared freely.
The following lists the benefits of using the Flyweight pattern:
- Reduction in the number of objects to handle
- Reduction in memory and on storage devices, if the objects are persisted
You should use the Flyweight pattern when all of the following are true.
- The application uses a large number of objects.
- Storage costs are high because of the quantity of objects.
- The application does not depend on object identity.