KenPowerClassroom / SoftwareEngineeringforGamesI

3 stars 0 forks source link

Flyweight Pattern #82

Open kenpower opened 2 years ago

kenpower commented 2 years ago

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

  1. Divide fields of a class that will become a flyweight into two parts:
  1. 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.

  2. 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.

  3. 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