Flyweight Pattern
A Flyweight is one immutable object shared by every context that needs that exact value. You take the fields of what would otherwise be a million objects and split them in two: the part that is identical across uses gets stored once and handed out by reference, and the part that varies per use stays outside and is passed in at the call. A thousand spreadsheet cells drawn in Calibri 11 bold hold a thousand pointers to one CellStyle, not a thousand copies of the same handful of fields.
💡 Intrinsic state = the part that is shared and context-free: the rank and suit of a card, the glyph for a character, the sprite for a tree. Extrinsic state = the part that is per-use and supplied by the caller: which position on the board, which pixel it draws at, which player is holding the card. The split is the pattern – get it wrong and there is nothing safe to share.
Why this matters: Flyweight is the one structural pattern whose justification is arithmetic, and interviewers use it to test two things at once. First, whether you notice an object explosion inside your own design – a CellStyle per cell, a Card per dealt card, a tile object per board square – rather than waiting to be told. Second, whether you understand that sharing imposes immutability: a design that shares a mutable object has not saved memory, it has bought a bug that reproduces only under the exact data that happens to share. The Java flavour of this question is “why does == work for Integer 127 and fail for 128”, which is a Flyweight question wearing a different hat.
Prerequisites
- Immutability and Equality – a shared object that can be written to is a bug every holder sees, and the shared pool never gets a hit unless
equalsandhashCodeare correct - Factory Pattern – callers must never
newa flyweight, so a factory owns the pool and decides whether to build one or hand back one that exists - Collections and Complexity – the pool is a hash map keyed by the value itself, and what one lookup costs is the entire cost side of this trade
The Problem: a spreadsheet where every cell owns its own CellStyle
A spreadsheet makes the counts concrete. Every cell has to know how it is drawn, so the obvious design gives every cell a CellStyle of its own, built in the Cell constructor and edited through setters:
// Mutable, no equals, no hashCode. One instance per cell.
public class CellStyle {
private String fontFamily = "Calibri";
private int sizePt = 11;
private boolean bold;
private boolean italic;
private int argbColour = 0xFF000000;
private Alignment align = Alignment.LEFT;
public void setBold(boolean bold) { this.bold = bold; }
// ... one setter and one getter per field
}
public class Cell {
private final int row;
private final int col;
private String value = "";
private final CellStyle style = new CellStyle(); // a fresh style per cell
public Cell(int row, int col) { this.row = row; this.col = col; }
public CellStyle style() { return style; }
}
public class Sheet {
private final Cell[][] cells = new Cell[1000][100]; // 100,000 cells
public Sheet() { // ...and 100,000 CellStyle objects, one
for (int r = 0; r < 1000; r++) // per cell, however many look identical
for (int c = 0; c < 100; c++) cells[r][c] = new Cell(r, c);
}
/** Six compares to answer "do these two cells look the same". */
private boolean sameStyle(CellStyle a, CellStyle b) {
return a.getFontFamily().equals(b.getFontFamily())
&& a.getSizePt() == b.getSizePt()
&& a.isBold() == b.isBold()
&& a.isItalic() == b.isItalic()
&& a.getArgbColour() == b.getArgbColour()
&& a.getAlign() == b.getAlign();
}
/** "Select every cell that looks like this one": 100,000 deep compares. */
public List<Cell> cellsStyledLike(Cell target) {
return Arrays.stream(cells).flatMap(Arrays::stream)
.filter(c -> sameStyle(c.style(), target.style()))
.collect(Collectors.toList());
}
}
Three costs, in the order they bite:
- The arithmetic, and it is an estimate. A 1000-row by 100-column sheet is 100,000 cells, and because each constructor runs
new CellStyle(), 100,000 style objects. Assume each one’s fields come to roughly 60-80 bytes – two object references, two ints, two booleans, padded to an 8-byte boundary – and add the JVM’s 16-byte object header, and the sheet carries on the order of 8-10 MB of style data. That is arithmetic from a stated assumption, not a measurement – the real figure moves with the JVM, compressed references and alignment – so do not quote it as a benchmark. The ratio is what matters: a real sheet has perhaps a dozen distinct appearances, so those 8-10 MB encode about a kilobyte of actual information. - Equal styles are not
==. Two cells that look identical hold two unrelated objects, so asking whether their appearance matches is a field-by-field walk, assameStylemakes embarrassingly literal.cellsStyledLikeis therefore O(n) deep comparisons rather than O(n) pointer compares, and “list the distinct styles in this sheet” needs a hand-writtenequalsandhashCodeover all six fields before aHashSetdoes anything at all. - A style is not a thing. There is nowhere to hang a named style like Heading 1, because a style here is a smear of equal-but-separate values across whichever cells happen to agree.
Class Diagram
classDiagram
class CellStyle {
-String fontFamily
-int fontSizePt
-int argbColour
-boolean bold
+withBold(boolean) CellStyle
+equals(Object) boolean
+hashCode() int
}
class CellStyleFactory {
-ConcurrentMap pool
+intern(CellStyle) CellStyle
+of(family, sizePt, argb, bold) CellStyle
+distinctStyles() int
}
class Cell {
-int row
-int col
-String value
+setBold(boolean)
+style() CellStyle
}
class Sheet {
-List~Cell~ cells
+applyBoldToColumn(int col)
+cellsStyledLike(Cell) List~Cell~
}
CellStyleFactory --> CellStyle
Cell --> CellStyle
Sheet --> Cell
Sheet --> CellStyleFactory
The non-obvious part is that Cell --> CellStyle is many-to-one and one-directional: a hundred thousand cells point at a handful of styles, and nothing on CellStyle lets a cell write through that pointer. CellStyleFactory is the only code that constructs a style, which is what makes “equal styles” and “the same style object” the same statement.
💡 Interning = replacing a value you just built with the canonical instance equal to it, so every holder of that value ends up pointing at one object. Learn more →
Real-World Example: Spreadsheet Cell Styles
// ---- The flyweight: deeply immutable, value-equal, and its own pool key ----
public final class CellStyle {
private final String fontFamily; // String is itself a flyweight, see below
private final int fontSizePt;
private final int argbColour;
private final boolean bold; // four of the six fields, to keep equals short
// Package-private: only the factory builds one, so no caller ends up holding
// an un-interned instance by accident.
CellStyle(String fontFamily, int fontSizePt, int argbColour, boolean bold) {
this.fontFamily = Objects.requireNonNull(fontFamily);
this.fontSizePt = fontSizePt;
this.argbColour = argbColour;
this.bold = bold;
}
/** A style edit returns the pooled variant. It never writes to this object. */
public CellStyle withBold(boolean value) {
if (value == bold) return this; // no allocation, no pool lookup
return CellStyleFactory.intern(
new CellStyle(fontFamily, fontSizePt, argbColour, value));
}
// equals and hashCode over every field, or the pool never hits. A record
// generates exactly this pair; spelled out because the pool rests on it.
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof CellStyle other)) return false;
return fontSizePt == other.fontSizePt
&& argbColour == other.argbColour
&& bold == other.bold
&& fontFamily.equals(other.fontFamily);
}
@Override public int hashCode() {
return Objects.hash(fontFamily, fontSizePt, argbColour, bold);
}
}
// ---- The factory owns the one pool ----
public final class CellStyleFactory {
// Key and value are the same object on purpose. A Set would tell you only
// whether the style was absent; a Map can hand the canonical instance back.
private static final ConcurrentMap<CellStyle, CellStyle> POOL = new ConcurrentHashMap<>();
public static final CellStyle DEFAULT = of("Calibri", 11, 0xFF000000, false);
private CellStyleFactory() { }
/** computeIfAbsent is one atomic put-if-absent, so two threads racing on the
* same style get the same instance, never two equal ones. A get-then-put
* pair loses that race and breaks the one guarantee callers rely on. */
public static CellStyle intern(CellStyle candidate) {
return POOL.computeIfAbsent(candidate, key -> key);
}
public static CellStyle of(String family, int sizePt, int argb, boolean bold) {
return intern(new CellStyle(family, sizePt, argb, bold));
}
/** The number you quote when asked whether this actually paid off. */
public static int distinctStyles() { return POOL.size(); }
}
// ---- The context: extrinsic state lives here, the style is borrowed ----
public final class Cell {
private final int row; // extrinsic: where this cell sits
private final int col;
private String value; // extrinsic: what it holds
private CellStyle style; // intrinsic: shared, swapped but never written to
public Cell(int row, int col) {
this.row = row;
this.col = col;
this.style = CellStyleFactory.DEFAULT; // 100,000 cells, one style object
}
/** Swings the reference. It does not reach into the style. */
public void setBold(boolean bold) { this.style = style.withBold(bold); }
public CellStyle style() { return style; }
}
// ---- What it buys, in the two places anyone notices ----
Cell[][] grid = new Cell[1000][100];
for (int r = 0; r < 1000; r++)
for (int c = 0; c < 100; c++) grid[r][c] = new Cell(r, c); // no style copies
for (Cell[] row : grid) row[0].setBold(true); // bold the header column
CellStyleFactory.distinctStyles(); // 2, behind 100,000 cells
// Style comparison collapses to one pointer compare instead of a four-field walk,
// and a style index can hash on identity -- IdentityHashMap, not HashMap.
CellStyle target = grid[0][0].style();
long matching = Arrays.stream(grid).flatMap(Arrays::stream)
.filter(cell -> cell.style() == target).count();
from dataclasses import dataclass
from functools import lru_cache
@dataclass(frozen=True, slots=True)
class CellStyle:
"""frozen=True gives immutability plus __eq__ and __hash__ -- exactly the pair
the pool needs. slots=True drops the per-instance __dict__, the other half of
the win, and it matters most on Cell, the class there are 100,000 of."""
font_family: str = "Calibri"
size_pt: int = 11
argb: int = 0xFF000000
bold: bool = False
def with_bold(self, bold: bool) -> "CellStyle":
if bold == self.bold:
return self
# NOT dataclasses.replace: that returns a fresh, un-interned instance,
# equal to a pooled one but not identical, so `is` quietly stops working.
return cell_style(self.font_family, self.size_pt, self.argb, bold)
@lru_cache(maxsize=4096)
def cell_style(font_family: str = "Calibri", size_pt: int = 11,
argb: int = 0xFF000000, bold: bool = False) -> CellStyle:
"""lru_cache IS the intern pool: same arguments, same object back, interning
for free. maxsize bounds it, which a plain dict never does, and that is safe
only because an evicted style stays alive while a Cell still references it.
Trap: the key is the argument tuple, so cell_style() and
cell_style("Calibri", 11) are two entries holding two equal-but-distinct
objects. Always pass every argument, or normalise at one call site."""
return CellStyle(font_family, size_pt, argb, bold)
class Cell:
__slots__ = ("row", "col", "value", "style") # no __dict__ per cell
def __init__(self, row: int, col: int) -> None:
self.row, self.col = row, col # extrinsic
self.value = "" # extrinsic
self.style = cell_style() # intrinsic, shared
def set_bold(self, bold: bool) -> None:
self.style = self.style.with_bold(bold)
sheet = [[Cell(r, c) for c in range(100)] for r in range(1000)]
for row in sheet:
row[0].set_bold(True)
cell_style.cache_info() # currsize=2, behind 100,000 cells
sheet[0][0].style is sheet[1][0].style # True, so `is` is a valid style compare
#include <cstdint>
#include <memory>
#include <mutex>
#include <string>
#include <unordered_map>
struct CellStyle {
std::string fontFamily = "Calibri";
int sizePt = 11;
std::uint32_t argb = 0xFF000000u;
bool bold = false;
bool operator==(const CellStyle&) const = default; // C++20, member-wise
};
struct CellStyleHash {
std::size_t operator()(const CellStyle& s) const noexcept {
std::size_t h = std::hash<std::string>{}(s.fontFamily);
h = h * 31 + static_cast<std::size_t>(s.sizePt);
h = h * 31 + s.argb;
return h * 31 + (s.bold ? 1u : 0u);
}
};
// `const` in the pointee type is the compiler-enforced version of the immutability
// rule: the Java and Python tabs promise it by convention, while here a holder that
// tries to write through its style fails to compile.
using StylePtr = std::shared_ptr<const CellStyle>;
class CellStyleFactory {
std::unordered_map<CellStyle, StylePtr, CellStyleHash> pool_;
mutable std::mutex m_;
public:
StylePtr intern(const CellStyle& candidate) {
std::lock_guard<std::mutex> guard(m_);
auto it = pool_.find(candidate);
if (it != pool_.end()) return it->second;
auto shared = std::make_shared<const CellStyle>(candidate);
pool_.emplace(candidate, shared);
return shared;
}
StylePtr withBold(const StylePtr& base, bool bold) {
if (base->bold == bold) return base;
CellStyle edited = *base; // copy, edit the copy, re-intern
edited.bold = bold;
return intern(edited);
}
// Bounding the pool without weak references: use_count() == 1 means the pool
// is the last holder, so dropping it is invisible. use_count is a snapshot --
// sweep at a quiesce point, not while threads are copying StylePtrs.
void sweepUnused() {
std::lock_guard<std::mutex> guard(m_);
for (auto it = pool_.begin(); it != pool_.end(); )
it = (it->second.use_count() == 1) ? pool_.erase(it) : std::next(it);
}
};
class Cell {
int row_, col_; // extrinsic
std::string value_; // extrinsic
StylePtr style_; // intrinsic, shared
public:
Cell(int row, int col, StylePtr style)
: row_(row), col_(col), style_(std::move(style)) {}
bool sameStyleAs(const Cell& other) const {
return style_.get() == other.style_.get(); // one pointer compare
}
// style_->bold = true; // will not compile: the pointee is const
};
// A shared_ptr costs two words per cell plus atomic refcount traffic on every copy.
// Where the pool outlives every sheet, a raw `const CellStyle*` is one word and no
// atomics.
Sharing only works if the shared part cannot change
Here is the exact bug. Suppose CellStyle keeps its setBold method from the broken version. A user bolds cell A1, your code calls a1.style().setBold(true), and every one of the 99,999 other cells pointing at that same default style turns bold too. One click bolds the sheet. A flyweight must be immutable. Not “should be” – the pattern is unsound without it. An edit returns a different flyweight; the context swings its pointer.
Three things come with that rule:
- Correct
equalsandhashCodeare mandatory, not hygiene. With inherited identity equality, everyinterncall is a miss, the pool grows one entry per call, and you have shipped the original memory problem plus a hash map. The symptom isdistinctStyles()climbing with cell count instead of flattening. Javarecords and frozen Python dataclasses generate the pair for you, which is the real reason to reach for them here. - The pool is a cache, so it is a leak until you bound it. A
ConcurrentHashMapholding every style ever requested keeps them alive forever. The historical lesson isString.intern(): before Java 7 the pool lived in PermGen, so interning untrusted input was a reliable way to exhaust a JVM.WeakHashMapis the usual reach, and the trap is that it only works when the value does not reference the key – aWeakHashMap<CellStyle, CellStyle>with the same object on both sides is strongly self-referential and collects nothing. You needWeakHashMap<CellStyle, WeakReference<CellStyle>>, a bounded LRU, or the C++ tab’s reference-count sweep. - A flyweight is a terrible lock target.
synchronized (cell.style())serialises two completely unrelated cells, and nothing at either call site hints at why. The textbook version is locking on a boxedInteger:synchronized (Integer.valueOf(1))contends with every other piece of code in the JVM doing the same thing, because they all lock the one cached object. Shared objects must not be monitors. Concurrency covers the lock-granularity side; Immutability and Equality covers making the sharing safe in the first place.
The flyweights already in your language
Interviewers expect these by name, because they are the pattern shipped as a language feature:
- Java
String. Literals go into the constant pool, so two occurrences of"Calibri"in source are one object.String.intern()is the manual version, and==on interned strings is legitimate – which is why==on strings built at runtime is a classic bug. - Java
Integer.valueOf. The JDK caches boxes for -128 through 127, the upper bound tunable via-XX:AutoBoxCacheMax. This is whyInteger a = 127, b = 127; a == bistruewhile the same code with 128 isfalse: small values come from the pool, larger ones are freshly allocated.Long,Short,Byte,CharacterandBooleanhave the same caches, andnew Integer(128)is deprecated because it bypasses the pool. - Python. CPython preallocates the integers -5 through 256 and interns identifier-shaped string literals, which is why
256 is 256holds and257 is 257is not guaranteed.sys.intern()is the explicit hook.
Flyweight vs Singleton vs Object Pool vs Prototype vs Caching
All five hand you an object you did not just construct. What separates them is how many objects exist, who owns the lifetime, and whether the object can be written to:
| Pattern | Intent | Tell |
|---|---|---|
| Flyweight | Cut memory by sharing one immutable instance per distinct value | Many instances, exactly one per distinct value, and nobody can write to the shared part |
| Singleton | Exactly one instance globally, for identity or coordination | The count is one regardless of how many values exist, and it usually holds mutable state on purpose |
| Object Pool | Reuse objects that are expensive to create, by lending and reclaiming | The objects are mutable and must be handed back – borrow and release, the opposite contract |
| Prototype | Dodge construction cost by copying a configured instance | It copies, so you finish with more objects, not fewer |
| Plain caching | Avoid a recomputation or a fetch, keyed by a lookup key | Keyed by something other than the value, and free to evict and later return a fresh-but-equal object |
The overlap worth naming is Flyweight and caching, because a flyweight pool is a hash map with a hit rate. The contract differs: a cache may legally return an object merely equal to the one it handed out last time, while a flyweight pool must return the object, because callers are comparing with ==. That is why a flyweight pool may only evict a value no context still holds, and why eviction here is a correctness question rather than a tuning one.
When to Use vs When to Avoid
| Use Flyweight When | Avoid When |
|---|---|
| Many objects, few distinct values – cell styles, glyphs, board tiles, map sprites | The values are mostly distinct, so the pool ends up one entry per object |
| The shared part is genuinely immutable, or you can make it so | Each context needs to mutate its own copy of the shared part |
| Memory or GC pressure is the problem you actually measured | You have not measured, and the count is thousands rather than millions |
| You want value comparison to collapse into one pointer compare | A pointer chase per access sits on a hot path tighter than the memory saving |
Equality is already defined by value, with correct equals and hashCode |
Identity carries meaning – two equal values must stay distinguishable as lock targets or identity keys |
The characteristic failure mode is applying it with no measurement. Flyweight is a trade: you pay a pointer indirection on every access and a hash lookup on every style change, and you buy memory. With fifty cells, or with styles that are all distinct, you have paid both costs and bought nothing, and the code reads worse because a Cell no longer tells you what it looks like. The precondition is specific – many objects, few distinct values – and you should be able to say which numbers you mean: 100,000 cells, about a dozen styles. If you cannot name both, you are guessing, and Over-Engineering is the lesson that bites. The subtler cost is that intern(new CellStyle(...)) allocates a candidate on every call, so a loop interning per frame has traded long-lived data for short-lived garbage – usually a good trade, never a free one.
Interview Questions
-
“What breaks if a flyweight is mutable?” – One mutation is visible to every context holding it. Give
CellStyleasetBoldand bolding a single cell bolds every cell sharing that style, so a 100,000-cell sheet goes bold from one click. The nasty part is the blast radius – “whichever cells happened to share” – so the bug is data-dependent, invisible on a test sheet where every style is distinct, and unreproducible from a bug report. The correct shape isstyle.withBold(true)returning a different interned flyweight that the context then points at. -
“How do you bound the intern pool, and why is
WeakHashMapnot enough?” –WeakHashMapholds keys weakly, so an entry disappears once nothing else references the key. That fails immediately in the obvious flyweight layout, where the map’s value is the key: the strong value reference keeps the key alive and nothing is ever collected. The fix isWeakHashMap<K, WeakReference<V>>, which costs a dereference and a nullable get, or drop weakness and bound with an LRU, or reference-count and sweep as the C++ tab does. Pick one deliberately – a pool with no answer here is a slow memory leak with good intentions. -
“Flyweight vs Object Pool?” – Opposite contracts. An object pool lends out mutable objects – connections, buffers, threads – and the borrower must return them, because the point is amortising expensive construction and the object is exclusively yours while held. A flyweight is shared concurrently by every context wanting that value, is never returned, and must be immutable precisely because it is shared. If your “flyweight” has an
acquire/releasepair, it is a pool; if your “pool” hands one instance to two callers at once, it had better be immutable. -
“Why does
==work forInteger127 and not 128?” –Integer.valueOfis a flyweight factory whose cache covers -128 through 127, which the language spec requires, and autoboxing routes through it. SoInteger a = 127, b = 127both point at the cached object anda == bistrue, while 128 falls outside the cache, allocates two objects, and comparesfalse. The lesson is not the boundary, it is that identity comparison silently depends on whether a flyweight pool happened to cover your value – so compare boxed types withequals, and distrust any==that works only for small inputs. -
“The styles are shared now, but the extrinsic state is still large. Where should it live?” – Out of the objects entirely, in parallel arrays keyed by cell index: one
String[] values, oneint[] styleIds, onedouble[] numbers, with cell(r, c)atr * width + c. That is the same idea one step further: Flyweight removes the duplicated fields, a columnar layout removes the per-object wrapper around the fields that remain, so 100,000Cellheaders collapse into three arrays. It also turns “sum column C” into a contiguous walk instead of 1,000 pointer chases, which is why spreadsheet engines, column stores and entity-component systems all look like this. What you give up isCellas a thing you can pass around – index arithmetic and bounds checks become your problem – so reach for it when the count justifies it, not by default.
See It in Action
- Spreadsheet Engine –
CellStyleinterned exactly as above, with row, column and value staying on the cell - Deck of Cards – one immutable
Cardper rank-and-suit pair, so a six-deck shoe is 312 references to 52 objects and “same card” is a pointer compare - Text Editor – shared glyph and character-run styles hanging off a Composite document tree, with pixel position supplied by the renderer
- Chat Application – one interned
Userper participant, shared by every message in every room, so a million messages hold pointers, not copies of the sender