0
0
LldConceptBeginner · 3 min read

Flyweight Pattern: Definition, Example, and Usage

The Flyweight pattern is a design pattern that reduces memory use by sharing common parts of objects instead of creating duplicates. It stores shared data externally and passes unique data separately, making it efficient for many similar objects.
⚙️

How It Works

The Flyweight pattern works by separating an object's data into two parts: shared and unique. Imagine you have many similar objects, like trees in a forest. Instead of storing the same tree type information for each tree, you store one shared tree type object and reuse it for all trees of that type.

This is like having a single recipe card for a cake that many bakers use, instead of each baker writing their own copy. The unique details, like the tree's position, are stored separately. This way, memory is saved because the shared data is not duplicated.

💻

Example

This example shows a simple Flyweight pattern in Python where tree types are shared to save memory.

python
class TreeType:
    def __init__(self, name, color, texture):
        self.name = name
        self.color = color
        self.texture = texture

    def draw(self, x, y):
        print(f"Drawing {self.name} tree of color {self.color} at ({x}, {y})")

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

    def draw(self):
        self.tree_type.draw(self.x, self.y)

# Usage
factory = TreeFactory()
trees = []
trees.append(Tree(10, 20, factory.get_tree_type("Oak", "Green", "Rough")))
trees.append(Tree(15, 25, factory.get_tree_type("Oak", "Green", "Rough")))
trees.append(Tree(50, 60, factory.get_tree_type("Pine", "Dark Green", "Smooth")))

for tree in trees:
    tree.draw()
Output
Drawing Oak tree of color Green at (10, 20) Drawing Oak tree of color Green at (15, 25) Drawing Pine tree of color Dark Green at (50, 60)
🎯

When to Use

Use the Flyweight pattern when you have many objects that share a lot of common data and you want to save memory. It is especially useful in games, graphics, or any system with many similar objects like characters, trees, or icons.

For example, a forest simulation with thousands of trees can use Flyweight to share tree types instead of storing full data for each tree. It helps improve performance and reduce memory use.

Key Points

  • Flyweight separates shared (intrinsic) and unique (extrinsic) data.
  • It reduces memory by sharing common parts of objects.
  • Useful when many similar objects exist.
  • Requires managing shared objects carefully.

Key Takeaways

Flyweight pattern saves memory by sharing common object data.
It splits object data into shared and unique parts.
Ideal for systems with many similar objects like games or graphics.
Helps improve performance by reducing duplicate data.
Requires a factory or manager to handle shared objects.