0
0
LLDsystem_design~7 mins

Flyweight pattern in LLD - System Design Guide

Choose your learning style9 modes available
Problem Statement
When a system creates many objects with identical or similar data, memory usage grows rapidly, causing slow performance and high resource consumption. This often happens in graphical applications or text editors where many repeated elements exist, leading to inefficient memory use.
Solution
The Flyweight pattern reduces memory use by sharing common parts of objects instead of storing them separately. It separates intrinsic (shared) state from extrinsic (unique) state, storing shared data once and passing unique data externally when needed.
Architecture
Client
(requests) ─┼───────▶
(creates/shares)

This diagram shows how the client requests flyweight objects from the factory, which creates or reuses shared objects containing intrinsic state.

Trade-offs
✓ Pros
Significantly reduces memory usage by sharing common data among many objects.
Improves performance by lowering object creation overhead.
Enables handling large numbers of fine-grained objects efficiently.
✗ Cons
Increases complexity by separating intrinsic and extrinsic state.
Requires careful management of extrinsic state passed externally.
Not suitable if objects have mostly unique data with little shared state.
Use when your system creates millions of similar objects with large shared data, such as text editors rendering characters or graphical applications with repeated shapes.
Avoid when objects have mostly unique data or when the overhead of managing extrinsic state outweighs memory savings, typically under 10,000 objects.
Real World Examples
Microsoft
Microsoft Word uses flyweight to efficiently render millions of characters by sharing font and style data among characters.
Google
Google Maps uses flyweight to share map tile data among many map views, reducing memory use.
Adobe
Adobe Illustrator shares graphical object data to handle complex vector graphics with many repeated elements.
Code Example
The before code creates a new Tree object with full data for each instance, wasting memory. The after code separates shared data (TreeType) and unique data (coordinates), reusing TreeType objects to save memory.
LLD
### Before Flyweight (naive, no sharing)
class Tree:
    def __init__(self, x, y, type_):
        self.x = x
        self.y = y
        self.type = type_  # large data like tree type info

# Creating many trees with repeated type data
forest = [Tree(i, j, 'Oak') for i in range(1000) for j in range(1000)]


### After Flyweight (shared intrinsic state)
class TreeType:
    def __init__(self, name, color, texture):
        self.name = name
        self.color = color
        self.texture = texture

class TreeFactory:
    _tree_types = {}

    @classmethod
    def get_tree_type(cls, name, color, texture):
        key = (name, color, texture)
        if key not in cls._tree_types:
            cls._tree_types[key] = TreeType(name, color, texture)
        return cls._tree_types[key]

class Tree:
    def __init__(self, x, y, tree_type):
        self.x = x
        self.y = y
        self.tree_type = tree_type  # shared intrinsic state

# Creating many trees sharing TreeType objects
forest = []
for i in range(1000):
    for j in range(1000):
        tree_type = TreeFactory.get_tree_type('Oak', 'Green', 'Rough')
        forest.append(Tree(i, j, tree_type))
OutputSuccess
Alternatives
Prototype pattern
Creates new objects by cloning existing ones rather than sharing intrinsic state.
Use when: Choose when you need many similar but independent objects with slight variations.
Object Pool pattern
Reuses a fixed set of objects instead of sharing intrinsic data, focusing on object lifecycle management.
Use when: Choose when object creation is expensive and you want to reuse whole objects rather than parts.
Summary
Flyweight pattern reduces memory use by sharing common parts of many similar objects.
It separates shared intrinsic state from unique extrinsic state passed externally.
This pattern is ideal for systems with millions of fine-grained objects having repeated data.