StructuralC#verifiedVerified

Flyweight Pattern in C#

Minimizes memory usage by sharing fine-grained objects that represent repeated data, storing intrinsic state once and passing extrinsic state at call time.

How to Implement the Flyweight Pattern in C#

1Step 1: Flyweight stores shared (intrinsic) state

public class CharacterGlyph(char symbol, string fontFamily, int fontSize)
{
    public char Symbol => symbol;
    public string FontFamily => fontFamily;
    public int FontSize => fontSize;

    // Render with extrinsic state (position)
    public string Render(int x, int y) =>
        $"'{Symbol}' in {FontFamily} {FontSize}px at ({x},{y})";
}

2Step 2: Factory ensures sharing of flyweight instances

public class GlyphFactory
{
    private readonly Dictionary<string, CharacterGlyph> _cache = [];

    public CharacterGlyph GetGlyph(
        char symbol, string font, int size)
    {
        var key = $"{symbol}_{font}_{size}";

        if (!_cache.TryGetValue(key, out var glyph))
        {
            glyph = new CharacterGlyph(symbol, font, size);
            _cache[key] = glyph;
        }

        return glyph;
    }

    public int CacheSize => _cache.Count;
}

// Usage:
// var factory = new GlyphFactory();
// var a1 = factory.GetGlyph('A', "Arial", 12);
// var a2 = factory.GetGlyph('A', "Arial", 12);
// Console.WriteLine(ReferenceEquals(a1, a2)); // True

Flyweight Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Flyweight Pattern in the Real World

A book publisher doesn’t print a separate metal typeface block for every letter ‘e’ on every page. Instead, one block for ‘e’ (intrinsic state) is reused in every position, with the printer supplying the ink color and position (extrinsic state) each time it is stamped. Thousands of impressions share one piece of metal.