Structural

Flyweight

Shares common state between multiple objects to reduce memory usage.

Text editorsGame developmentCaching systems

Understanding Flyweight

The Flyweight pattern dramatically reduces memory usage by sharing common state between many similar objects instead of storing it redundantly in each one. It separates an object's state into intrinsic (shared, immutable) and extrinsic (unique per context) parts. In Go, a flyweight factory (usually using a map cache) creates and returns shared instances keyed by their intrinsic properties. This is essential for applications that create millions of similar objects — like characters in a text editor, particles in a game, or tree types in a forest renderer.

Key Concepts

  • Intrinsic state — shared data stored inside the flyweight object (e.g., tree type, font style) — immutable and reused
  • Extrinsic state — unique data stored outside the flyweight by the client (e.g., position, context) — passed to methods
  • Flyweight factory — ensures flyweight objects are shared by caching and returning existing instances from a map
  • Memory savings — instead of N objects × M bytes each, you have K shared flyweights + N lightweight contexts

When to Use

✅ Use when
  • • Your application creates a very large number of similar objects
  • • Most of each object's state can be made extrinsic (passed from outside)
  • • Groups of objects share substantial portions of their state
  • • The application struggles with memory consumption from many object allocations
⚠️ Avoid when
  • • Objects have mostly unique state that can't be shared
  • • The number of objects is small enough that memory isn't a concern
  • • The complexity of separating intrinsic/extrinsic state isn't worth the savings

Structure

Client (holds extrinsic state: x, y)
↓ GetFlyweight(key)
FlyweightFactory (cache map)
↓ returns shared
Flyweight A
Flyweight B

How It Works

Object 1
name, color, texture...
Object 2
name, color, texture...
Object 3
name, color, texture...
Object 4
name, color, texture...
Object 5
name, color, texture...
Object 6
name, color, texture...
Object 7
name, color, texture...
Object 8
name, color, texture...
Object 9
name, color, texture...
Object 10
name, color, texture...
Object 11
name, color, texture...
Object 12
name, color, texture...
⚠ High memory usage
1

Memory Problem

Creating many similar objects consumes lots of memory.

1 / 4

Basic Implementation

Forest rendering with shared tree type objects:

main.go
Loading editor...

Real-World Example: Text Editor

Character formatting with shared format objects:

main.go
Loading editor...