Flyweight: share the repeated part
Picture
Text and position differ, but font family and size repeat. Share the repeated style instead of copying it into every label.
Predict
Where should a label’s position live?
Walk through the small example
Outside the shared style. Position varies by use and must stay independent.
Mental model and complete Python solution
Flyweight separates intrinsic shared state from extrinsic per-use context. StyleFactory interns frozen Style objects by family and size. The pattern saves repeated representation, but does not bound the number of distinct configurations. Choose a lifetime or eviction policy when key cardinality can grow indefinitely.
What the function promises: Equal style keys return the same immutable object. Label data remains independently owned.
from dataclasses import dataclass
@dataclass(frozen=True)
class Style:
family: str
size: int
class StyleFactory:
def __init__(self):
self.styles = {}
def get(self, family, size):
if size <= 0:
raise ValueError("Invalid size")
key = family, size
if key not in self.styles:
self.styles[key] = Style(*key)
return self.styles[key]
factory = StyleFactory()
a = {"x": 10, "style": factory.get("Sans", 14)}
b = {"x": 50, "style": factory.get("Sans", 14)}
assert a["style"] is b["style"]
assert a["x"] != b["x"]
Work and storage: Expected O(1) lookup, O(distinct styles) shared storage.
When to recognize it: A factory reuses a style for each key. If every style is unique, the factory can still grow without bound.
Check before applying it: Shared intrinsic data should not contain per-use mutable state.
Change one rule
A caller wants to change the font of just one label. Should it mutate the shared style?
See what changes
No. Obtain another immutable style value and replace that label’s reference. Mutating shared state would affect every user of the same flyweight.
Connect
Let small objects work together: Share a helper only when its ownership and mutation rules permit it.
LRU Cache: Contrast immutable representation sharing with evictable cached results.