Flyweight Design Pattern



What is Flyweight Design Pattern ?

Flyweight pattern is used when you have multiple common shared objects that will be reused across multiple elements.

The objects don't change much in their values, instead, they share the same value in multiple places.

This raises an issue if we will create a new object every time we need to access one.

When to use Flyweight Design Pattern ?

Flyweight pattern is used as a performance optimization pattern. It's used to reduce the object creation overhead

If we have a GUI system and this system is using characters as elements pool. these characters are shared and don't change their values often.

We can share it and use when needed, then return the element to the pool when it's no longer needed.

How to implement Flyweight Design Pattern ?

The Flyweight pattern acts as a singleton pattern.

When we need to display a character, we pull it from the pool. if it's not created we create it and save in the pool.

The second time we need to display the same character we check if it's already in the pool other than creating the object each time we need to access it.

Is it useful in all cases ?

The Flyweight pattern is a performance optimization pattern. in most cases you will not need it. you will need 1/5 of the times


In theory, this pattern could improve performance, but in practice it's limited to scenarios where you find yourself creating a lot of objects from one or more templates. Further, the entire point of this pattern is to improve performance

performance is not an issue until you can prove that it is, so while refactoring to this pattern may be useful in some extreme circumstances, for most people and most projects the overhead and complexity of the Flyweight pattern outweigh the benefits.