Flyweight pattern

In this article I will describe the structural pattern “Flyweight”
This pattern refers to the group Structural Patterns.

Example of the pattern below:

Why is it needed? To save RAM memory. I agree that in times of widespread use of Java (which consumes cpu and memory just like that), this is not so important, but it’s worth it.
In the example above, only 40 objects are displayed, but if you raise their number to 120,000, the memory consumption will increase accordingly.
Let’s look at the memory consumption without using the flyweight pattern in the Chromium browser:

Without the use of the pattern, the memory consumption is ~ 300 megabytes.

Now add a pattern to the application and see the memory consumption:

With the use of the pattern, the memory consumption is ~ 200 megabytes, so we saved 100 megabytes of memory in the test application, in serious projects the difference can be much larger.

Wie funktioniert das?

In the example above, we draw 40 cats or, for clarity, 120 thousand. Each cat is loaded into memory as a png image, then in most renders it is converted into a bitmap for rendering (actually bmp), this is done for speed, since a compressed png is drawn for a very long time. Without using a pattern, we load 120 thousand pictures of cats into RAM and draw, but when using the lightweight pattern, we load one cat into memory and draw it 120 thousand times with different positions and transparency. All the magic lies in the fact that we implement the coordinates and transparency separately from the cat image, when rendering the render takes just one cat and uses an object with coordinates and transparency to correctly draw.

Show me the code

The following are examples for the Rise language.

Without a pattern:


The cat image is loaded for each object in the loop separately – catImage.

Using the pattern:

One cat picture is used by 120 thousand objects.

Real life example

It is used in GUI frameworks, for example, in Apple, in the “reuse” system of the cells of the UITableViewCell tables, which raise the entry threshold for beginners who do not know about this pattern.

Source code

https://gitlab.com/demensdeum/patterns/

Documents

https://refactoring.guru/en/design-patterns/flyweight
http://gameprogrammingpatterns.com/flyweight.html