Design Patterns

Pattern 11 of 23, Structural family

Flyweight

Save memory by sharing the common (intrinsic) state across a large number of objects.

The problem

A game renders 100,000 trees. If every tree stores its own 2 MB texture, RAM blows up even though only the coordinates differ.

The solution

Separate the intrinsic state (name, color, texture — shared, immutable) from the extrinsic state (x, y — specific to each object). A factory caches and reuses the flyweights.

The pattern in action

  • Client
  • Key role of the pattern
  • Object
  • Data or state
  1. The forest asks the factory for a tree type.
  2. Not cached: the heavy intrinsic state is created.
  3. The tree stores only x, y and a reference to the type.
  4. Another request for the same type…
  5. …already cached: the same instance is returned.
  6. 100,000 trees → a single texture in memory.

An analogy

In a word processor, each letter "a" does not hold its own copy of the font: they all point to the same glyph.

When to use it

  • Very large numbers of similar objects
  • Games, rendering, text editors, maps
  • Repetitive data (string caches, icon caches)

Pros and cons

Pros

  • Massive reduction in memory usage
  • Safe sharing thanks to immutability

Cons

  • Added complexity (separating the states)
  • Trades memory for CPU (recomputing extrinsic state)

Implementations

The same example, written idiomatically in each language.

Flyweight in Python

flyweight.py 25 lines
from dataclasses import dataclass
from functools import lru_cache


@dataclass(frozen=True)
class TreeType:                  # intrinsic state, shared and immutable
    name: str
    color: str
    texture: bytes


@lru_cache(maxsize=None)         # the flyweight "factory"
def tree_type(name: str, color: str) -> TreeType:
    return TreeType(name, color, texture=bytes(2_000_000))


@dataclass(slots=True)
class Tree:                      # extrinsic state, specific to each tree
    x: int
    y: int
    type: TreeType


forest = [Tree(i, i * 2, tree_type("Oak", "green")) for i in range(100_000)]
print(forest[0].type is forest[-1].type)   # True

Flyweight in TypeScript

flyweight.ts 28 lines
class TreeType {
  constructor(
    readonly name: string,
    readonly color: string,
    readonly texture: Uint8Array,
  ) {}
}

class TreeTypeFactory {
  private static cache = new Map<string, TreeType>();

  static get(name: string, color: string): TreeType {
    const key = name + "|" + color;
    let t = this.cache.get(key);
    if (!t) {
      t = new TreeType(name, color, new Uint8Array(2_000_000));
      this.cache.set(key, t);
    }
    return t;
  }
}

class Tree {
  constructor(public x: number, public y: number, private type: TreeType) {}
}

const forest = Array.from({ length: 100_000 },
  (_, i) => new Tree(i, i * 2, TreeTypeFactory.get("Oak", "green")));

Flyweight in Java

flyweight.java 18 lines
record TreeType(String name, String color, byte[] texture) {}

final class TreeTypeFactory {
    private static final Map<String, TreeType> CACHE = new ConcurrentHashMap<>();

    static TreeType get(String name, String color) {
        return CACHE.computeIfAbsent(name + "|" + color,
                k -> new TreeType(name, color, new byte[2_000_000]));
    }
}

record Tree(int x, int y, TreeType type) {}

List<Tree> forest = IntStream.range(0, 100_000)
        .mapToObj(i -> new Tree(i, i * 2, TreeTypeFactory.get("Oak", "green")))
        .toList();

// JDK example: Integer.valueOf(-128..127) returns shared instances

Flyweight in C#

flyweight.cs 17 lines
public sealed record TreeType(string Name, string Color, byte[] Texture);

public static class TreeTypeFactory
{
    private static readonly ConcurrentDictionary<(string, string), TreeType> Cache = new();

    public static TreeType Get(string name, string color) =>
        Cache.GetOrAdd((name, color), k => new TreeType(k.Item1, k.Item2, new byte[2_000_000]));
}

public readonly record struct Tree(int X, int Y, TreeType Type);

var forest = Enumerable.Range(0, 100_000)
    .Select(i => new Tree(i, i * 2, TreeTypeFactory.Get("Oak", "green")))
    .ToList();

// .NET example: string.Intern() shares identical strings

Flyweight in PHP

flyweight.php 29 lines
final class TreeType
{
    public function __construct(
        public readonly string $name,
        public readonly string $color,
        public readonly string $texture,
    ) {}
}

final class TreeTypeFactory
{
    private static array $cache = [];

    public static function get(string $name, string $color): TreeType
    {
        return self::$cache["$name|$color"]
            ??= new TreeType($name, $color, str_repeat('x', 2_000_000));
    }
}

final class Tree
{
    public function __construct(public int $x, public int $y, public TreeType $type) {}
}

$forest = [];
for ($i = 0; $i < 100_000; $i++) {
    $forest[] = new Tree($i, $i * 2, TreeTypeFactory::get('Oak', 'green'));
}

Flyweight in Go

flyweight.go 26 lines
type TreeType struct {
    Name, Color string
    Texture     []byte
}

var (
    mu    sync.Mutex
    cache = map[string]*TreeType{}
)

func GetTreeType(name, color string) *TreeType {
    mu.Lock()
    defer mu.Unlock()
    key := name + "|" + color
    if t, ok := cache[key]; ok {
        return t
    }
    t := &TreeType{name, color, make([]byte, 2_000_000)}
    cache[key] = t
    return t
}

type Tree struct {
    X, Y int
    Type *TreeType // shared pointer
}

Frequently asked questions

What is the Flyweight design pattern?

Save memory by sharing the common (intrinsic) state across a large number of objects. Separate the intrinsic state (name, color, texture — shared, immutable) from the extrinsic state (x, y — specific to each object). A factory caches and reuses the flyweights.

When should you use the Flyweight pattern?

Very large numbers of similar objects; Games, rendering, text editors, maps; Repetitive data (string caches, icon caches).

What are the pros and cons of the Flyweight pattern?

Pros: Massive reduction in memory usage; Safe sharing thanks to immutability. Cons: Added complexity (separating the states); Trades memory for CPU (recomputing extrinsic state).