In this note I will describe the structural pattern “Flyweight” or “Opportunist” (Flyweight)
This pattern belongs to the group of Structural patterns.
Let’s look at an example of the pattern below:
Why is it needed? To save RAM. I agree that in times of widespread use of Java (which consumes CPU and memory for no reason), this is no longer so important, but it is worth using.
The example above only displays 40 objects, but if we increase the number to 120,000, the memory consumption will increase accordingly.
Let’s look at memory consumption without using the flyweight pattern in the Chromium browser:
Without using the pattern, memory consumption is ~300 megabytes.
Now let’s add a pattern to the application and see the memory consumption:
Using the pattern, memory consumption is ~200 megabytes, so we saved 100 megabytes of memory in the test application, in serious projects the difference can be much greater.
How does it work?
In the example above, we draw 40 cats, or 120 thousand for clarity. Each cat is loaded into memory as a png image, then in most renderers it is converted to a bitmap for drawing (actually bmp), this is done for speed, since compressed png takes a very long time to draw. Without using a pattern, we load 120 thousand cat pictures 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 is that we implement the coordinates and transparency separately from the cat image, when drawing, the renderer takes only one cat and uses an object with coordinates and transparency for correct drawing.
What does it look like in code?
Below are examples for the Rise
language.
Without using a pattern:
The cat image is loaded for each object in the loop separately – catImage.
Using the pattern:
One picture of a cat is used by 120 thousand objects.
Where is it used?
Used in GUI frameworks, for example in Apple’s “reuse” system for UITableViewCell table cells, which raises the entry threshold for beginners who don’t know about this pattern. It is also widely used in game development.
Source code
https://gitlab.com/demensdeum/patterns/< /p>
Sources
https://refactoring.guru/ru/design-patterns/ flyweight
http://gameprogrammingpatterns.com/flyweight.html