GofPatterns Gofpatterns





Structural Patterns  «Prev  Next»

Flyweight Pattern

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.


Flyweight Pattern
  1. Flyweight Pattern Motivation
Benefits:
The following lists the benefits of using the Flyweight pattern:
  1. Reduction in the number of objects to handle
  2. Reduction in memory and on storage devices, if the objects are persisted
When to Use:
You should use the Flyweight pattern when all of the following are true.
  1. The application uses a large number of objects.
  2. Storage costs are high because of the quantity of objects.
  3. The application does not depend on object identity.