Skip to content

Flyweight

Context: Use sharing to support large numbers of fine‑grained objects efficiently.

public class Flyweight
{
private string _sharedState;
public Flyweight(string state) => _sharedState = state;
public void Operation(string uniqueState) => Console.WriteLine($"{_sharedState} + {uniqueState}");
}
public class FlyweightFactory
{
private Dictionary<string, Flyweight> _flyweights = new();
public Flyweight GetFlyweight(string key)
{
if (!_flyweights.ContainsKey(key))
_flyweights[key] = new Flyweight(key);
return _flyweights[key];
}
}

Text rendering: Each character in a document can share a Character flyweight with intrinsic state (font, size, style). The extrinsic state (position) is passed when drawing.

Example: In .NET, string interning is a flyweight: identical string literals share the same memory. Also, Int32 caching in -128 to 127 range.