Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
Py

Python

Readable, batteries-included, and the default language of AI.

Paradigm
Multi-paradigm, OOP, functional
Typing
Dynamic, strong, optional type hints
Memory
Reference counting + cycle GC
Runs
CPython bytecode interpreter
Concurrency
asyncio, threads (GIL), multiprocessing
Structural pattern

Flyweight

Intent

Fits more objects into RAM by sharing common state between many objects.

Problem

A particle system with millions of particles runs out of memory because each stores its own sprite.

Solution

Split intrinsic (shared, immutable) state from extrinsic (per-use) state and share the intrinsic part.

Real-world analogy

Think of it like this

A game forest: thousands of trees share a handful of tree models. Only each tree's position and size are stored separately.

Structure

association / extends implements / depends on
Client 4 Context - uniqueState- flyweight+ operation() 2 FlyweightFactory - cache: Flyweight[]+ getFlyweight(repeatingState) 3 Flyweight - repeatingState+ operation(uniqueState) 1

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Flyweight — Flyweight stores the intrinsic state shared between many objects.
  2. 2Context — Context holds the extrinsic, unique state and pairs it with a flyweight.
  3. 3FlyweightFactory — Flyweight Factory manages a pool and returns an existing flyweight when one matches.
  4. 4Client — Client calculates or stores the extrinsic state.

Code example

A Python code sample for Flyweight is coming soon. Factory Method, Singleton, Decorator, Observer and Strategy already have code in all six languages.

Applicability

Use Flyweight when the program must support huge numbers of similar objects and RAM is tight.

Pros and cons

Pros

  • Large memory savings

Cons

  • Trades RAM for CPU
  • Code becomes more complicated

Relations with other patterns

Check yourself

Check yourself

A text editor renders millions of characters, and the glyph data is identical for most of them.

Saved in this browser only. Part of Structural patterns (0/7).