Flyweight Pattern

From Logic Wiki
Jump to: navigation, search


Reduce memory usage by sharing common (intrinsic) state between many objects, instead of storing it repeatedly.

What problem it solves

When:

  • you need huge numbers of similar objects
  • most of their data is identical
  • memory or performance becomes an issue

…you share instead of duplicate.

Core idea

Intrinsic state → shared, immutable (stored in flyweight)

Extrinsic state → supplied from outside at runtime

public class CharacterFlyweight
{
    public char Symbol { get; }
    public string Font { get; }

    public CharacterFlyweight(char symbol, string font)
    {
        Symbol = symbol;
        Font = font;
    }

    public void Draw(int x, int y) // extrinsic state
    {
        Console.WriteLine($"Drawing '{Symbol}' at ({x},{y})");
    }
}


public class CharacterFactory
{
    private readonly Dictionary<char, CharacterFlyweight> _cache = new();

    public CharacterFlyweight Get(char symbol)
    {
        if (!_cache.ContainsKey(symbol))
        {
            _cache[symbol] = new CharacterFlyweight(symbol, "Arial");
        }
        return _cache[symbol];
    }
}

Usage

var factory = new CharacterFactory();

var a1 = factory.Get('A');
var a2 = factory.Get('A');

Console.WriteLine(ReferenceEquals(a1, a2)); // true

Why people use it

  • Massive memory savings
  • Faster object creation
  • Scales well for large datasets

When to use it

  • Text editors (characters, fonts)
  • Game objects (trees, bullets, tiles)
  • Caching-heavy systems

One-line memory hook

If millions of objects look the same → Flyweight