Flyweight Design Pattern
Explore the Flyweight design pattern to understand how to reduce memory usage by sharing immutable, heavyweight objects across multiple lightweight instances. Learn to apply this pattern in Kotlin to optimize resource consumption in applications like 2D games, enhancing performance on memory-limited devices.
We'll cover the following...
Flyweight object
A flyweight is an object without any state. The name comes from it being very light. This might sound similar to another object that should be very light: a data class. But a data class is all about state.
So, is the data class related to the Flyweight design pattern at all?
To understand the Flyweight design pattern better, we need to jump back in time. In the early 1990s, a regular PC had 4 MB of RAM. During this period, one of the main goals of any process was to save that precious RAM, because we could fit only so much into it.
Nowadays, some cellphones have 8 GB of RAM.
Having said that, let’s see how we can use our resources more efficiently, as this is always important!
Being conservative
Imagine we’re building a 2D side-scrolling arcade platform game. That is, we have our game character, which we control with arrow keys or a gamepad. Our character can move left, right, and jump.
Since we’re a really small indie company consisting of one developer (who is also a graphic designer, product manager, and sales ...