Flyweight Pattern

Flyweight pattern enforces using the same instance of object if its all properties are same. It leads to use less memory.

In this pattern, an object has two states:

  1. Intrinsic: state that does not change and can be shared
  2. Extrinsic: state with variable data and cannot be shared.

So, instead of keeping both of these states together and creating many instances of same class for different values of extrinsic state while keeping the intrinsic state same, we can split these states. Or we can just remove extrinsic state and provide from outside if required.

Example below shows this effect.

a1 = Glyph(width=6, ascent=9, descent=3, x=32, y=8)
a2 = Glyph(width=6, ascent=9, descent=3, x=8, y=60)

a1 and a2 shares same state for width, ascent and descent. A glyph will usually have same physical properties across different positional positional properties. This can be improved if we split it into to classes.

a = Glyph(width=6, ascent=9, descent=3)
a1 = DrawnGlyph(glyph=a, x=32, y=8)
a2 = DrawnGlyph(glyph=a, x=8, y=60)

Flyweight Factory

A flyweight factory is a factory which returns same instance of the class if it already exists and creates and stores the otherwise.

However, this is approached different in Python using constructor where this can be decided in the constructor itself if a new instance needs to returned.

References

  1. https://python-patterns.guide/gang-of-four/flyweight/
  2. https://en.wikipedia.org/wiki/Flyweight_pattern