Design Pattern Download: The Flyweight Pattern

Matthew MacFarquhar
2 min readMar 25, 2022

--

The Flyweight pattern is a Structural Pattern used in software engineering when we want to have a very large number of similar objects that take up a lot of memory and would exhaust our RAM.

Example

We are creating a virtual forest in our hot new game! each tree needs a tree sprite stored as a byte array, an x coordinate and a y coordinate. You successfully create 10 trees and decide to scale up to create your 10k forest when BANG! You run out of memory! What happened? you dig a little deeper and realize that each tree needs 4 bytes for the x-coord, 4 bytes for the y-coord and 10MB for the sprite! So… (10MB + 4B + 4B) * 10,000 ~ 100GB which is much larger than our available RAM :/. However, you also realize that the sprite is exactly the same for all trees and the only thing that changes is the x and y coords. So you split up the fields into two classes and re-use the reference for the class with the sprite for all 10k trees so now your memory usage is 20MB + (4B + 4B)*10,000 = 20MB + 80KB ~ 20MB. Now your game runs lighting fast! this is the power of the Flyweight. It splits your object into variable low memory variables and immutable high memory variables.

When to use the Flyweight?

  • When you want to have a large number of high memory objects in your application which do not fit into RAM but share some immutable properties.

What is the Flyweight Pattern composed of?

  • The Resource class ( the class containing the high memory, immutable, shared values)
  • The Instance class(the class containing the lower memory fields which vary object to object)

Implementation

The Resource

The Instance

Now we can create 10k trees and pass in the reference to the Resource so they all use the same one, avoiding an “OutOfMemmory Error”.

--

--

Matthew MacFarquhar
Matthew MacFarquhar

Written by Matthew MacFarquhar

I am a software engineer working for Amazon living in SF/NYC.

No responses yet