Introduction to the Flyweight pattern

The Gang of Four states that a Flyweight is a shared object that can be used in multiple contexts simultaneously. Similarly to flyweight in boxing, which is the lightweight boxing category, we can have a lighter object that can be used in different places in our system simultaneously.

While not used terribly often nowadays, the Flyweight pattern can be very helpful in scenarios when memory is constrained.

A Flyweight will consist of two parts: the intrinsic state and the extrinsic state. The intrinsic state is the part that can be shared. The extrinsic state is modified based on the context it's being used in and, as such, cannot be shared.

Let's take a look at a UML diagram to see a closer look:

We have the FlyweightFactory class, which is used to manage the Flyweights. Whenever we request one, we will either give one that's been created or create a new one ourselves.

The Flyweight object itself has data that is of whatever type is needed, as long as it won't change depending on the object that we're working with.

Finally, we have the ConcreteFlyweight, which acts as our extrinsic information that can access and use our Flyweight via the FlyweightFactory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.135.216.75