Flyweight Pattern
Share repeated immutable state while keeping per-use data such as position separate.
· Last updated: 2026-11-07 · 8 min read
Overview
A document may contain ten thousand glyphs but only a few font-and-size combinations. A style object per glyph then duplicates the same state that many times, and memory rises with the glyph count.
To cut that duplication, pick out the state several objects can share. The shared side is intrinsic state; the part that changes with each use, such as position, is extrinsic state. Flyweight is the name for keeping the two apart, and the example splits style and placement along that line.
UML
The diagram shows where that split lands in classes. StylePool reuses a GlyphStyle per font-and-size pair, and PlacedGlyph refers to that style but keeps its own letter and X coordinate.
History
GoF cataloged Flyweight as a structural pattern in Design Patterns in 1994. It uses shared state to support many small objects with less duplicated storage.1
Flyweight originated directly in Paul Calder and Mark Linton's 1990 ACM UIST paper on Glyphs in the InterViews toolkit and the Doc document editor.2 By keeping only character code and font metrics inside shared glyph objects while passing screen coordinates and layout state as extrinsic parameters during drawing, they represented every single character in a 100,000-character document as an object without blowing memory.
Why use it?
Separating the state that can be shared from the state each item keeps lets the same style be reused. Style objects stay at one per combination, no matter how many glyphs arrive. Editing a shared object changes every item that references it, though, so the example keeps GlyphStyle immutable.
The approach has a cost. A pool grows as new keys keep arriving. Set the retention scope and the cleanup policy first, then adopt the pool only after measuring whether the workload actually needs the memory reduction.
Example
Here the same style is requested twice, and the returned references are compared.
The pool is empty on the first Get("Serif", 16) call. It cannot find the font-and-size key, so it creates a GlyphStyle, stores it, and returns the reference. On the second call, it finds the key and returns that stored reference. ReferenceEquals is true because both calls return the same object.
using System;
using System.Collections.Generic;
using System.Linq;
var pool = new StylePool();
Console.WriteLine(ReferenceEquals(pool.Get("Serif", 16), pool.Get("Serif", 16)));
// Put only immutable, shareable values in the style object.
sealed record GlyphStyle(string Font, int Size);
sealed record PlacedGlyph(char Letter, int X, GlyphStyle Style);
// Reuse the object for the same key instead of constructing a style per placement.
sealed class StylePool
{
private readonly Dictionary<(string Font, int Size), GlyphStyle> styles = new();
public int Count => styles.Count;
public GlyphStyle Get(string font, int size)
{
var key = (font, size);
if (!styles.TryGetValue(key, out var style))
{
style = new GlyphStyle(font, size);
styles.Add(key, style);
}
return style;
}
}
TrueStylePool returns the object it already created instead of constructing two equal style objects.
An extended example
This time two letters at different positions refer to the same style. Because position is kept out of the style, the sharing still holds.
Two PlacedGlyph objects show how characters at different positions can use the same style settings. Each placement keeps its own character and coordinate: A with 0, and B with 20. Both Style references point to the same object obtained from the pool.
There are two placement objects but only one style in the pool, which produces styles: 1. Font and size are the values chosen for sharing here. Keeping character and coordinate in each placement lets them vary independently.
using System;
using System.Collections.Generic;
using System.Linq;
var pool = new StylePool();
var letters = new[]
{
new PlacedGlyph('A', 0, pool.Get("Serif", 16)),
new PlacedGlyph('B', 20, pool.Get("Serif", 16))
};
foreach (var letter in letters) Console.WriteLine(letter.Letter + "@" + letter.X);
Console.WriteLine("styles: " + pool.Count);
// Put only immutable, shareable values in the style object.
sealed record GlyphStyle(string Font, int Size);
sealed record PlacedGlyph(char Letter, int X, GlyphStyle Style);
// Reuse the object for the same key instead of constructing a style per placement.
sealed class StylePool
{
private readonly Dictionary<(string Font, int Size), GlyphStyle> styles = new();
public int Count => styles.Count;
public GlyphStyle Get(string font, int size)
{
var key = (font, size);
if (!styles.TryGetValue(key, out var style))
{
style = new GlyphStyle(font, size);
styles.Add(key, style);
}
return style;
}
}
A@0
B@20
styles: 1The letters and positions differ; their style is shared. Singleton limits a class to one instance, while this pool shares one object per font-and-size combination. Both cut the object count, but they draw the line in different places. This pool is used on one thread.
TypeScript example
This is the same split carried over to TypeScript. Glyphs share font and size, while letter and position are kept per placement. With that split, the common style stays reusable, and moving the position of one glyph leaves the others untouched.
// Put only immutable, shareable values in the style object.
class GlyphStyle {
constructor(readonly font: string, readonly size: number) { Object.freeze(this); }
}
type PlacedGlyph = Readonly<{ letter: string; x: number; style: GlyphStyle }>;
// Reuse the object for the same key instead of constructing a style per placement.
class StylePool {
private readonly fonts = new Map<string, Map<number, GlyphStyle>>();
get(font: string, size: number): GlyphStyle {
let sizes = this.fonts.get(font);
if (!sizes) { sizes = new Map(); this.fonts.set(font, sizes); }
let style = sizes.get(size);
if (!style) { style = new GlyphStyle(font, size); sizes.set(size, style); }
return style;
}
get count(): number { return [...this.fonts.values()].reduce((n, sizes) => n + sizes.size, 0); }
}
const pool = new StylePool();
const letters: PlacedGlyph[] = [
{ letter: "A", x: 0, style: pool.get("Serif", 16) },
{ letter: "B", x: 20, style: pool.get("Serif", 16) },
];
for (const glyph of letters) console.log(glyph.letter + "@" + glyph.x);
console.log("styles: " + pool.count);A@0
B@20
styles: 1Object.freeze keeps the shared style immutable, and the pool looks up both font and size. That is how the immutability requirement shows up in code. Retention and size limits are separate policies omitted from this example.
Immutability, loss of object identity, and pool retention pitfalls
Two invariants govern every Flyweight implementation. First, intrinsic state must be strictly immutable: because dozens or thousands of contexts alias the same instance, mutating a single field on a shared flyweight corrupts every caller simultaneously. Second, callers must never rely on object identity to distinguish conceptual items: two separate characters on screen intentionally point to the exact same GlyphStyle address in memory, so identity checks (ReferenceEquals or ===) reflect value sharing rather than distinct document positions.
Watch the lifetime of the flyweight pool itself as well. A static dictionary that caches every key it ever sees prevents the garbage collector from reclaiming unused entries; if keys come from unbounded user input, the pool becomes a memory leak that costs more RAM than it saves. Bound the pool to a finite set of canonical keys, or pair it with an eviction policy or weak references when the key space is open-ended.
Related reading
Footnotes
- Gamma, Helm, Johnson, Vlissides. Design Patterns (1994). Publisher record. Structural patterns, Flyweight. ↩
- Paul R. Calder and Mark A. Linton, "Glyphs: Flyweight Objects for User Interfaces," Proceedings of the 3rd Annual ACM SIGGRAPH Symposium on User Interface Software and Technology (UIST '90), 1990, pp. 92–101. DOI. ↩