Flyweight Design Pattern

Flyweight Design Pattern

Design Pattern Serie

Intent

It let us fit more objects into the available amount of RAM by reusing already existing similar kinds of objects after storing them. It creates new objects when There is no matching object found.

Problem

Imagine that we have a website with 500 images where each image takes around 0.2 of a second to be loaded, so we will wait for about 2 minutes to load that website every time we refresh the page!!
So do you think there is a solution for this?

Solution

We can make the browser load all the new images and cache them. So for already loaded images, a flyweight object is created, It will have unique data (information about the image) like position within the page, and everything else will be referenced to these cached ones.

Pros and Cons

Pros

  • If we have a big number of similar objects in the program, then we can save lots of RAM and increases performance.

Cons

  • The code becomes more complicated as we need to add extra logic for storing and retrieving the extrinsic states.

  • The data owned previously by each object and accessed directly must now be retrieved through what seems like a Factory, so we might be trading RAM over CPU cycles when some of the data needs to be recalculated.

Thank you, and goodbye.