StructuralPythonverifiedVerified

Flyweight Pattern in Python

Minimizes memory usage by sharing fine-grained objects that represent repeated data, storing intrinsic state once and passing extrinsic state at call time.

How to Implement the Flyweight Pattern in Python

1Step 1: Define the shared intrinsic state

from dataclasses import dataclass


@dataclass(frozen=True)
class CharacterStyle:
    font: str
    size: int
    bold: bool

2Step 2: Create the Flyweight that holds shared state

@dataclass(frozen=True)
class Character:
    char: str
    style: CharacterStyle

    def render(self, x: int, y: int) -> None:
        bold = " bold" if self.style.bold else ""
        print(f'"{self.char}" [{self.style.font} {self.style.size}px{bold}] @ ({x},{y})')

3Step 3: Build a factory that pools and reuses flyweights

class CharacterFactory:
    def __init__(self) -> None:
        self._pool: dict[str, Character] = {}

    def get(self, char: str, style: CharacterStyle) -> Character:
        key = f"{char}|{style.font}|{style.size}|{style.bold}"
        if key not in self._pool:
            self._pool[key] = Character(char, style)
            print(f'[Factory] created flyweight for key "{key}"')
        return self._pool[key]

    @property
    def pool_size(self) -> int:
        return len(self._pool)

4Step 4: Render text and verify flyweight reuse

factory = CharacterFactory()
style = CharacterStyle("Arial", 12, False)

# Rendering "ABBA" -- "A" and "B" flyweights are reused
for i, ch in enumerate("ABBA"):
    factory.get(ch, style).render(i * 10, 0)

print("Flyweights in pool:", factory.pool_size)  # 2, not 4

Flyweight Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Flyweight Pattern in the Real World

A book publisher doesn’t print a separate metal typeface block for every letter ‘e’ on every page. Instead, one block for ‘e’ (intrinsic state) is reused in every position, with the printer supplying the ink color and position (extrinsic state) each time it is stamped. Thousands of impressions share one piece of metal.