Sitemap
Biswajit Sahoo

Biswajit Sahoo

Software dev who writes about C#, AI, Unity, and XR or anything trending in simpler words.

C# Design Patterns: Flyweight

5 min readJul 30, 2023

--

Press enter or click to view image in full size
Flyweight C# Design Pattern

Thanks for visiting this article. Please scroll down for the bite-sized explanation of this pattern.

Definition

The Flyweight Pattern is a structural design pattern that aims to minimize memory consumption by sharing common data across similar objects.

It achieves this by caching the intrinsic (shared) data of an object and adding extrinsic (unique) data to modify the cached object while using it.

Ideally, this pattern should only be used, if and only if your application requires creating and managing a lot of instances that can potentially cause a shortage of RAM.

Intrinsic and Extrinsic Data?

Take Candy-Crush as an example. Each “Candy” 🍬 is an instance, and has some properties, that make them similar to other candies yet they behave differently when interacted.

Which properties do you think, can be referred to the common or unique types?

Intrinsic Data: These data are referred to as the immutable common (shared) data each object shares with others. i.e. Candy’s Mesh/texture, Candy’s Scale, and Candy’s Color

Extrinsic Data: These data are unique to each object and are not shared. Represents immutable and context-specific characteristics of the objects. i.e. Candy’s position in the grid

Let’s understand this from an example

Consider the same example of the Candy-Crush game. In the game, there are multiple candies of different colours and shapes that appear on the game in a grid.

Disclaimer: Not in any way, I’m showing the actual game mechanics here, nor do any of the code shown here belong to the game’s actual codebase.

Let’s see how we approach to do this if we were to make a similar type of game with lots of candies on the screen, > 10000s of them.

Clearly, we require a Candy class that can be instantiated for each candy we will show on the screen with a different shape and colour.

Note: The code examples may or may not have syntax, or compilation errors, and are for representational purposes only

Press enter or click to view image in full size
Candy class

In order to make them appear on the screen, let’s create a CandySpawner class that can spawn these candies at a position.

Press enter or click to view image in full size
CandySpawner class

Here’s the Game class, that spawns and positions the candies in a grid. (To ease the grid management we have a helper Grid class that holds the candies for their position on the grid)

Press enter or click to view image in full size
Game class

Alright, we have now the base functionalities ready.

Everything looks good, and now we can draw a grid of “candies” for custom row and column count.

So what’s the issue? ⚠️

Get Biswajit Sahoo’s stories in your inbox

Join Medium for free to get updates from this writer.

Well, mainly two✌ ️major issues:

❌ Memory Overhead: As candies with the same colour and shape are repeatedly created, memory is wasted on storing duplicate properties, increasing memory consumption

❌ Performance Impact: Frequent creation of new ‘Candy’ objects impacts the game’s performance, as it involves unnecessary memory allocations and deallocations.

In fact, the above issues are directly relative to the number of candies we are spawning and clearing each time.

Row ≤ 100 and Col ≤ 100, are still manageable by modern phones, but what about Row > 100 and Col > 100 😵‍💫 🤯. We’ll be holding at least 10000 instances of “candies” with duplicate properties in memory.

Although no mobile game should show these many objects to players, otherwise uninstallation of your game is inevitable, it’s just an example

Then how do we improve this, and still manage the same number of “candies” on screen? 🤔

Implementing the Flyweight Pattern

As explained earlier, before implementing this pattern, we need to identify the intrinsic and extrinsic properties of a “Candy” instance.

And those are:

  • Colour and Shape are the intrinsic (shared) property that a candy can be of certain colour and shape.
  • And the positions (x & y) are extrinsic (unique) property that is unique to a “Candy” instance.

Let’s refactor the Candy class so that we have a clear separation of these properties, and the Grid helper class will manage the positions of Candy instances.

Press enter or click to view image in full size
Candy class holding intrinsic properties

Next, we need to create a CandyFactory class that can hold the already-created candy instances and return the same instance when asked.

Press enter or click to view image in full size
CandyFactory class

And we can get rid of the CandySpawner class. 🗑

With the factory created, it's time to refactor the Game class, so that instead of creating a new Candy instance every time, we will use the factory to reuse already created Candy instances for the game.

Press enter or click to view image in full size
Game class using CandyFactory to get cached Candy instances

And with the CandyFactory class that acts as a pool to manage shared candies, it ensures that we have only one instance of a particular candy (e.g., red circular candy) in memory, regardless of how many times that candy appears on the game grid/board.

And that’s all to it 😃

By implementing the Flyweight Pattern, we have:

✅ Increase Memory Efficiency: By sharing common candy properties (i.e., colour, shape), we avoid redundant storage of these properties for each Candy instance, reducing memory consumption significantly

✅ Improved Performance: Reduced number of Candy objects created and managed each time, leading to faster execution times.

✅ Improved Scalability: Allowing the game to handle a large number and variety of candies efficiently, enabling a smooth gaming experience for the players.

Hope this helped with giving you some clarity on how this pattern can be implemented and used in a real-world scenario.

On the last note. If you like the article please do like and share, and also feel free to provide your valuable comments and feedback.

--

--

Biswajit Sahoo

Written by Biswajit Sahoo

Software dev who writes about C#, AI, Unity, and XR or anything trending in simpler words.