Scan with Phone

Scan to instantly open and share this page on your mobile device.

Link copied to clipboard!

Flyweight

Share intrinsic state; externalize extrinsic (context).

C#

// Flyweight object: "intrinsic" state = the character itself.
class Glyph
{
    public char C { get; }
    public Glyph(char c) => C = c;

    // Render uses "extrinsic" state (x,y) supplied from the outside each time.
    public void Draw(int x, int y) => Console.WriteLine($"{C}@{x},{y}");
}

// Factory manages shared instances (pool / cache)
class GlyphFactory
{
    private readonly Dictionary _cache = new();

    public Glyph Get(char c)
    {
        if (!_cache.TryGetValue(c, out var g))
        {
            g = new Glyph(c);        // create only once per distinct char
            _cache[c] = g;
        }
        return g;
    }

    public int Count => _cache.Count; // how many distinct flyweights
}

// Usage
var factory = new GlyphFactory();
var a1 = factory.Get('a');
var a2 = factory.Get('a');
var b1 = factory.Get('b');

bool sameA = ReferenceEquals(a1, a2);   // true (reused)
bool diffAB = ReferenceEquals(a1, b1);   // false
int distinct = factory.Count;            // 2

// Demonstrate extrinsic state (positions differ, object reused)
a1.Draw(10, 5);  // a@10,5
a2.Draw(11, 5);  // a@11,5 (same flyweight instance, different coords)
b1.Draw(3, 9);   // b@3,9
next