Use the Flyweight pattern only when your program must support a huge number of objects which barely fit into available RAM.
It’s most useful when:
an application needs to spawn a huge number of similar objects
this drains all available RAM on a target device
the objects contain duplicate states which can be extracted and shared between multiple objects
How to Implement
Divide fields of a class that will become a flyweight into two parts:
the intrinsic state: the fields that contain unchanging data duplicated across many objects (flyweight)
the extrinsic state: the fields that contain contextual data unique to each object (context)
Leave the fields that represent the intrinsic state in the class, but make sure they’re immutable. They should take their initial values only inside the constructor.
Optionally, create a factory class to manage the pool of flyweights. It should check for an existing flyweight before creating a new one. Once the factory is in place, clients must only request flyweights through it. They should describe the desired flyweight by passing its intrinsic state to the factory.
The client must store or calculate values of the extrinsic state (context) to be able to call methods of flyweight objects. For the sake of convenience, the extrinsic state along with the flyweight-referencing field may be moved to a separate context class.
Use the Flyweight pattern only when your program must support a huge number of objects which barely fit into available RAM.
It’s most useful when:
How to Implement
Leave the fields that represent the intrinsic state in the class, but make sure they’re immutable. They should take their initial values only inside the constructor.
Optionally, create a factory class to manage the pool of flyweights. It should check for an existing flyweight before creating a new one. Once the factory is in place, clients must only request flyweights through it. They should describe the desired flyweight by passing its intrinsic state to the factory.
The client must store or calculate values of the extrinsic state (context) to be able to call methods of flyweight objects. For the sake of convenience, the extrinsic state along with the flyweight-referencing field may be moved to a separate context class.
https://gameprogrammingpatterns.com/flyweight.html
https://refactoring.guru/design-patterns/flyweight