The Flyweight Pattern

Learn about the Flyweight pattern and how it differs from the Singleton pattern in Python.

Overview

The Flyweight pattern is a memory optimization pattern. Novice Python programmers tend to ignore memory optimization, assuming the built-in garbage collector will take care of it. Relying on built-in memory management is the best way to start. In some cases, for example, very large data science applications, memory constraints can become barriers, and more active measures need to be taken. In very small Internet of Things devices, memory management can also be helpful.

The Flyweight pattern ensures that objects that share a state can use the same memory for their shared state. It is normally implemented only after a program has demonstrated memory problems. It may make sense to design an optimal configuration from the beginning in some situations, but bear in mind that premature optimization is the most effective way to create a program that is too complicated to maintain.

In some languages, a Flyweight design requires careful sharing of object references, avoiding accidental object copying, and careful tracking of object ownership to ensure that objects aren’t deleted prematurely. In Python, everything is an object, and all objects work through consistent references. A Flyweight design in Python is generally somewhat simpler than in other languages.

Describing the Flyweight pattern

Let’s have a look at the following UML diagram for the Flyweight pattern:

Get hands-on with 1200+ tech skills courses.