Flyweight Pattern in Python
Flyweight separates shared intrinsic state from the unique state supplied for each use.
What is Flyweight Pattern?
Flyweight separates shared intrinsic state from the unique state supplied for each use.
Share reusable state across many small objects to reduce memory use.
When should you use it?
- Solve recurring object-design problems with proven structures.
- Decouple responsibilities so code is easier to extend and test.
- Use shared design vocabulary when discussing architecture with a team.
Example code
main.py
class Glyph:
# Flyweight: share repeated intrinsic state between many uses.
def __init__(self, character): self.character = character
class GlyphFactory:
_cache = {}
def get(self, character):
# Reuse immutable intrinsic state.
return self._cache.setdefault(character, Glyph(character))
factory = GlyphFactory()
first = factory.get("A")
second = factory.get("A")
print(first is second)
print(first.character)
Expected output
True
A
How it works
GlyphFactory caches one glyph per character while positions remain external.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Replace the sample domain while preserving the pattern structure.
- Compare the pattern with a simpler implementation and explain the tradeoff.
- Write tests for each participant before adding another implementation.