Flyweight: Introduction

Get a brief introduction to the Flyweight design pattern.

The Flyweight design pattern makes it possible to cram large quantities of objects without using too much memory. This is made possible by sharing some part of the state between the objects.

For example, imagine a real-time strategy game where we can build huge armies. Each unit is a separate object. However, units can have certain states that make them behave differently. For example, a shielded unit behaves differently from a unit without a shield. So, instead of giving the full set of possible behaviors to each unit, why not simply create two instances of an object representing the behavior—shielded and unshielded, and then simply link each unit to one of those instances?

Summarized concept of the Flyweight design pattern

Flyweight can be summarized as follows:

  • Flyweight object represents a set of some properties.
  • Flyweight Factory allows us to select a specific instance of the Flyweight object.
  • Objects intended to be multiplied can access a specific instance of the Flyweight object via the Flyweight Factory.

Get hands-on with 1400+ tech skills courses.