Flyweight Design Pattern in Python

Manage efficiently large numbers of similar objects to avoid RAM

Esteban Thilliez
Tech Tavern

--

Manage efficiently large numbers of similar objects to avoid RAM issues
Photo by Luan Gjokaj on Unsplash

This story is part of the “Design Patterns” series. You can find the other stories of this series here:

You can also find all the code used through this series on GitHub.

The Flyweight pattern is a design pattern used in computer programming to efficiently manage large numbers of similar objects. The idea is to use shared, immutable objects to represent data, and to use separate, mutable objects to hold the state that varies between instances.

Problems the Flyweight Pattern can Solve

Imagine we’re building a game where there are thousands of trees in the game world. Each tree has a unique location, size, and type, but they all share the same texture.

The naive solution is the following:

import time
from unittest.mock import Mock
import random


Image = Mock()
Image.open = lambda image: time.sleep(0.00001)


class Tree:
def…

--

--

Esteban Thilliez
Tech Tavern

I’m Esteban, and I enjoy writing about programming, trading, productivity, knowledge management, books, etc! esteban-thilliez.com / contact@esteban-thilliez.com