Search⌘ K

Flyweight

Explore how the Flyweight design pattern helps reduce memory usage by sharing intrinsic state among many fine-grained objects. Understand the difference between intrinsic and extrinsic states and see how this pattern optimizes applications that handle large numbers of similar objects, such as an aircraft radar system, enabling you to create memory-efficient and flexible software solutions.

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 ...