# Design patterns: Flyweight

> The Flyweight design pattern with examples in PHP

- URL: https://mautoblog.com/en/posts/design-patterns/flyweight/
- Language: en
- Published: 2024-09-27
- Updated: 2026-10-14
- Author: Mauto
- Categories: Software Development, Technology
- Tags: Software Architecture, Best Practices, PHP
- Guide: Design Patterns (part 12)
- Translation (it): https://mautoblog.com/posts/design-patterns/flyweight/

---
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
```php
// 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](/en/posts/design-patterns/)

