The flyweight pattern is used when there is a need to construct a huge number of objects with essentially identical properties and some common data. A few shared objects can replace many non-shared ones.
Concepts of Flyweight Design Pattern
The flyweight pattern makes use of both intrinsic and extrinsic data.
Intrinsic Data: The shared flyweight objects' characteristics store intrinsic data. This information is stateless and normally unchanging; if something changes, it will be reflected in all objects that reference the flyweight.
Extrinsic Data: Extrinsic data is computed during runtime and stored outside of a flyweight object. As a result, it has the potential to be meaningful.
Examples of Flyweight Design Patterns
Examples of flyweight patterns are:
Game Objects
Social Media Posts
List of Users
Flyweight Design Pattern with UML diagram
The classes, interfaces, and objects in the above UML class diagram are listed below:
Flyweight: This interface defines the properties of flyweight objects.
ConcreteFlyweight: This class inherits from the Flyweight class.
UnsharedFlyweight: This class inherits from the Flyweight class and allows for information sharing; instances of concrete flyweight classes can be created that are not shared.
FlyweightFactory: This class manages a set of pre-built flyweight objects. When the client invokes the GetFlyweight method, it determines whether the requested flyweight object exists in the collection. If it's found, it's returned; otherwise, a new object is generated, added to the collection, and returned.
When to use a Flyweight Design Pattern?
The flyweight design pattern is excellent for creating a huge number of similar products with high storage costs.
A few shared objects can replace many non-shared ones.
The majority of the state can be stored on disc or calculated during runtime.