Flyweight
Share common state between thousands of similar objects instead of duplicating it in each β trade CPU for RAM when you're running out of memory.
Intent & Description
π― Intent
Reduce memory consumption by sharing the intrinsic (shared) state across many similar objects, keeping only the extrinsic (unique) state per instance.
π Context
You’re rendering 100,000 trees in a game world, each with a position, scale, and type. Storing the full mesh, texture, and material for each tree object would exhaust RAM. Most trees of the same type share identical visual data β only their position differs.
π‘ Solution
Split object state into intrinsic (shared, immutable β tree type, texture, mesh) and extrinsic (unique per instance β position, scale). Create one Flyweight object per intrinsic state combination. Pass extrinsic state as method arguments. A FlyweightFactory caches and returns shared instances.
Real-world Use Case
Source
π TL;DR
Share the common bits, keep only the unique bits per instance. Thousands of objects, fraction of the RAM. Niche pattern β apply only when memory is a real constraint, not a premature optimization.
Advantages
- Massive RAM savings when thousands of objects share the same core data.
Disadvantages
- Adds CPU cost when shared data needs recalculation with per-instance context.
- Code becomes significantly more complex β separating intrinsic/extrinsic state isn’t always obvious.
class Book {
constructor(title, author, isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
}
class BookFactory {
constructor() { this.books = new Map(); }
createBook(title, author, isbn) {
if (!this.books.has(isbn)) {
this.books.set(isbn, new Book(title, author, isbn));
}
return this.books.get(isbn);
}
}