Flyweight

This lesson discusses how the flyweight pattern can be applied to reduce memory requirements.

What is it ?

Flyweight is a category in boxing competitions for light weight boxers. The intent of the pattern is somewhat similar in that it tries to reduce bloated code to a more compact and lean representation, which uses less memory.

Formally, the pattern is defined as sharing state among a large number of fine-grained objects for efficiency.

Class Diagram

The class diagram consists of the following entities

  • Flyweight
  • Concrete Flyweight
  • Unshared Concrete Flyweight
  • Flyweight Factory
  • Client
widget

Example

Following OO principles to the core may lead you to create too many objects in your application that have part of their state shared. For instance, continuing with our aircraft scenario, if you are designing a global radar that tracks all the planes currently airborne in the world at any time then your radar screen will show thousands of airplanes represented as objects in memory. If your hardware is limited in memory then you have a problem.

Each object would have some shared state that is independent of where the plane is flying in the world. This state which is independent of the context of the plane is called intrinsic state ...