Flyweight
Save memory by sharing the common (intrinsic) state across a large number of objects.
- 6 animated steps
- 6 languages
- Structural patterns
The problem
A game renders 100,000 trees. If every tree stores its own 2 MB texture, RAM blows up even though only the coordinates differ.
The solution
Separate the intrinsic state (name, color, texture — shared, immutable) from the extrinsic state (x, y — specific to each object). A factory caches and reuses the flyweights.
The pattern in action
- Client
- Key role of the pattern
- Object
- Data or state
- The forest asks the factory for a tree type.
- Not cached: the heavy intrinsic state is created.
- The tree stores only x, y and a reference to the type.
- Another request for the same type…
- …already cached: the same instance is returned.
- 100,000 trees → a single texture in memory.
An analogy
In a word processor, each letter "a" does not hold its own copy of the font: they all point to the same glyph.
When to use it
- Very large numbers of similar objects
- Games, rendering, text editors, maps
- Repetitive data (string caches, icon caches)
Pros and cons
Pros
- Massive reduction in memory usage
- Safe sharing thanks to immutability
Cons
- Added complexity (separating the states)
- Trades memory for CPU (recomputing extrinsic state)
Implementations
The same example, written idiomatically in each language.
Flyweight in Python
from dataclasses import dataclass
from functools import lru_cache
@dataclass(frozen=True)
class TreeType: # intrinsic state, shared and immutable
name: str
color: str
texture: bytes
@lru_cache(maxsize=None) # the flyweight "factory"
def tree_type(name: str, color: str) -> TreeType:
return TreeType(name, color, texture=bytes(2_000_000))
@dataclass(slots=True)
class Tree: # extrinsic state, specific to each tree
x: int
y: int
type: TreeType
forest = [Tree(i, i * 2, tree_type("Oak", "green")) for i in range(100_000)]
print(forest[0].type is forest[-1].type) # True
Flyweight in TypeScript
class TreeType {
constructor(
readonly name: string,
readonly color: string,
readonly texture: Uint8Array,
) {}
}
class TreeTypeFactory {
private static cache = new Map<string, TreeType>();
static get(name: string, color: string): TreeType {
const key = name + "|" + color;
let t = this.cache.get(key);
if (!t) {
t = new TreeType(name, color, new Uint8Array(2_000_000));
this.cache.set(key, t);
}
return t;
}
}
class Tree {
constructor(public x: number, public y: number, private type: TreeType) {}
}
const forest = Array.from({ length: 100_000 },
(_, i) => new Tree(i, i * 2, TreeTypeFactory.get("Oak", "green")));
Flyweight in Java
record TreeType(String name, String color, byte[] texture) {}
final class TreeTypeFactory {
private static final Map<String, TreeType> CACHE = new ConcurrentHashMap<>();
static TreeType get(String name, String color) {
return CACHE.computeIfAbsent(name + "|" + color,
k -> new TreeType(name, color, new byte[2_000_000]));
}
}
record Tree(int x, int y, TreeType type) {}
List<Tree> forest = IntStream.range(0, 100_000)
.mapToObj(i -> new Tree(i, i * 2, TreeTypeFactory.get("Oak", "green")))
.toList();
// JDK example: Integer.valueOf(-128..127) returns shared instances
Flyweight in C#
public sealed record TreeType(string Name, string Color, byte[] Texture);
public static class TreeTypeFactory
{
private static readonly ConcurrentDictionary<(string, string), TreeType> Cache = new();
public static TreeType Get(string name, string color) =>
Cache.GetOrAdd((name, color), k => new TreeType(k.Item1, k.Item2, new byte[2_000_000]));
}
public readonly record struct Tree(int X, int Y, TreeType Type);
var forest = Enumerable.Range(0, 100_000)
.Select(i => new Tree(i, i * 2, TreeTypeFactory.Get("Oak", "green")))
.ToList();
// .NET example: string.Intern() shares identical strings
Flyweight in PHP
final class TreeType
{
public function __construct(
public readonly string $name,
public readonly string $color,
public readonly string $texture,
) {}
}
final class TreeTypeFactory
{
private static array $cache = [];
public static function get(string $name, string $color): TreeType
{
return self::$cache["$name|$color"]
??= new TreeType($name, $color, str_repeat('x', 2_000_000));
}
}
final class Tree
{
public function __construct(public int $x, public int $y, public TreeType $type) {}
}
$forest = [];
for ($i = 0; $i < 100_000; $i++) {
$forest[] = new Tree($i, $i * 2, TreeTypeFactory::get('Oak', 'green'));
}
Flyweight in Go
type TreeType struct {
Name, Color string
Texture []byte
}
var (
mu sync.Mutex
cache = map[string]*TreeType{}
)
func GetTreeType(name, color string) *TreeType {
mu.Lock()
defer mu.Unlock()
key := name + "|" + color
if t, ok := cache[key]; ok {
return t
}
t := &TreeType{name, color, make([]byte, 2_000_000)}
cache[key] = t
return t
}
type Tree struct {
X, Y int
Type *TreeType // shared pointer
}
Frequently asked questions
What is the Flyweight design pattern?
Save memory by sharing the common (intrinsic) state across a large number of objects. Separate the intrinsic state (name, color, texture — shared, immutable) from the extrinsic state (x, y — specific to each object). A factory caches and reuses the flyweights.
When should you use the Flyweight pattern?
Very large numbers of similar objects; Games, rendering, text editors, maps; Repetitive data (string caches, icon caches).
What are the pros and cons of the Flyweight pattern?
Pros: Massive reduction in memory usage; Safe sharing thanks to immutability. Cons: Added complexity (separating the states); Trades memory for CPU (recomputing extrinsic state).