Design patterns: Flyweight

date: · 3 min
author: Mauto
series: Design Patterns/ part 12/24

The classic Gang of Four patterns, one per part, with practical PHP examples.

  1. Design Patterns
  2. Design patterns: Singleton
  3. Design patterns: Factory Method
  4. Design patterns: Abstract Factory
  5. Design patterns: Builder
  6. Design patterns: Prototype
  7. Design patterns: Adapter
  8. Bridge Pattern in PHP: What It Is, When to Use It, with Examples
  9. Design patterns: Composite
  10. Design patterns: Decorator
  11. Design patterns: Facade, What It Is and How to Use It (PHP)
  12. Design patterns: Flyweight
  13. Design patterns: Proxy
  14. Design patterns: Chain of Responsibility Explained (PHP)
  15. Design patterns: Command
  16. Design patterns: Interpreter
  17. Design patterns: Iterator
  18. Design patterns: Mediator
  19. Design patterns: Memento
  20. Design patterns: Observer
  21. Design patterns: State, What It Is and How to Use It (PHP)
  22. Design patterns: Strategy
  23. Design patterns: Template Method
  24. Design patterns: Visitor
the whole guide >

The Flyweight Pattern is a structural pattern used to reduce memory consumption and improve efficiency in applications that have to manage a large number of similar objects. The core idea is to share common objects (flyweights) across multiple entities, avoiding unnecessary duplication. The immutable “flyweight” objects are shared, while the variable parts are managed separately.

Characteristics of the Flyweight pattern

  1. Reduced memory usage: It drastically reduces the amount of memory used by sharing, across multiple entities, the objects that have common, immutable properties.
  2. Efficiency: The pattern improves efficiency when large volumes of objects are created and managed, especially in contexts where the objects differ from one another only in minor ways.
  3. Object reuse: It makes it easier to reuse similar objects, minimizing the need to recreate the same data multiple times within the system.
  4. Separation of intrinsic and extrinsic state: The intrinsic state (immutable and shared) is kept separate from the extrinsic state (instance-specific). This allows objects to be managed more efficiently.
  5. Trade-off between memory and complexity: The memory savings come at a cost: separating intrinsic from extrinsic state and managing sharing through a factory adds some complexity to the code.

Use Case

Suppose we have to manage a large map of characters in a game, where each character has an icon but little variable information. Instead of creating a new icon instance for every single character, we can use the Flyweight Pattern to share icons among all similar characters.

PHP Code

// Flyweight - Shared object
class CharacterIcon {
    private $icon; // Intrinsic state (shared)

    public function __construct($icon) {
        $this->icon = $icon;
    }

    public function render($x, $y) {
        echo "Rendering icon '{$this->icon}' at position ($x, $y)\n";
    }
}

// Flyweight Factory - Manages object sharing
class CharacterIconFactory {
    private $icons = [];

    public function getIcon($icon) {
        if (!isset($this->icons[$icon])) {
            $this->icons[$icon] = new CharacterIcon($icon);
        }
        return $this->icons[$icon];
    }

    public function countIcons() {
        return count($this->icons);
    }
}

// Client - Uses the flyweight objects with extrinsic state
class Game {
    private $iconFactory;
    private $characters = [];

    public function __construct() {
        $this->iconFactory = new CharacterIconFactory();
    }

    public function addCharacter($icon, $x, $y) {
        // Shared flyweight + extrinsic state (the character's position)
        $this->characters[] = [
            'icon' => $this->iconFactory->getIcon($icon),
            'x' => $x,
            'y' => $y,
        ];
    }

    public function render() {
        foreach ($this->characters as $character) {
            $character['icon']->render($character['x'], $character['y']);
        }
        echo "Characters: " . count($this->characters) . ", shared icons (flyweights): " . $this->iconFactory->countIcons() . "\n";
    }
}

// Usage
$game = new Game();
$game->addCharacter('knight', 10, 20);
$game->addCharacter('knight', 15, 25);
$game->addCharacter('dragon', 30, 40);
$game->addCharacter('knight', 50, 60);
$game->render();
/*
Output:
Rendering icon 'knight' at position (10, 20)
Rendering icon 'knight' at position (15, 25)
Rendering icon 'dragon' at position (30, 40)
Rendering icon 'knight' at position (50, 60)
Characters: 4, shared icons (flyweights): 2
*/

Explanation

  • CharacterIcon represents the intrinsic (immutable) state that is shared among all characters of the same type.
  • CharacterIconFactory manages the creation and sharing of CharacterIcon objects to avoid creating duplicates.
  • Game stores the characters: each one has a reference to the shared icon and its own position on the map. The extrinsic state (position) is variable and not shared.
  • The render() method draws all the characters and shows how many icons the factory created: 4 characters share only 2 flyweight objects.

Conclusion

The Flyweight Pattern is ideal when you’re dealing with a large number of similar objects that share many common properties, enabling significant memory savings and improving the application’s performance.

BACK TO THE GUIDE

Copied