The flyweight pattern is useful when dealing with large numbers of objects with simple repeated elements that would use a large amount of memory if individually stored. It is common to hold shared data in external data structures and pass it to the objects temporarily when they are used.
Where is flyweight pattern used?
Flyweight pattern is used when we need to create a large number of similar objects (say 105). One important feature of flyweight objects is that they are immutable. This means that they cannot be modified once they have been constructed.
How is flyweight implemented?
How to Implement
- Divide fields of a class that will become a flyweight into two parts: ...
- Leave the fields that represent the intrinsic state in the class, but make sure they're immutable. ...
- Go over methods that use fields of the extrinsic state. ...
- Optionally, create a factory class to manage the pool of flyweights.