Flyweight
medium 50 minThe Flyweight pattern shares what is the same in very many objects.
Watch lesson4:45
Where it shows up
The same pattern appears across everyday software.
Java: String.intern and literals
The class String keeps a pool. `intern` returns the one string from the pool that is equal to yours, and all literals are in it.
Java: Integer.valueOf
Always caches values from -128 to 127 and may cache others. That is why == seems to work for small numbers.
CPython: small integers
The current C API documentation says that integers between -5 and 1024 are kept in an array and shared. It marks this as an implementation detail.
Swing: table cell renderers
A JTable uses one renderer component as a rubber stamp for all cells, as the documentation puts it: set its content, draw it at the cell, go on to the next.
Unity: GPU instancing
One draw call renders many objects with the same mesh and material. The manual names trees and bushes as examples.
Godot: MultiMesh
A single draw primitive that can draw up to millions of objects. One mesh, an array of places.
three.js: InstancedMesh
For a large number of objects with the same geometry and material. Each instance has its own matrix.
Boost.Flyweight
Small handle classes that give constant access to shared data. Factory, locking and lifetime are configurable.
Guava: Interners
Strong and weak interners for any immutable type. The weak one does not prevent its objects from being collected.
pandas: categorical data
A column with few different strings is stored as codes and one list of categories. The user guide gives saved memory as a reason.