Patterncore
Flyweight pattern
Also called Flyweight, interning, hash consing, instance cache.
Share one immutable object between many uses, and pass the state that differs between the uses in as arguments. A factory hands out the shared objects, so that each value has one object.
- Family
- structural-design
- Intent
- Use sharing to support large numbers of fine-grained objects at a low cost in memory.
Intent
Use sharing to support large numbers of fine-grained objects at a low cost in memory.1 A flyweight is a shared object that can be used in many contexts at the same time. It holds only the state that is the same in all of them. Each use passes the rest of the state in as an argument.
Problem
Design Patterns starts with a document editor. An editor that makes each character an object gets a uniform design: characters, lines and pages are all objects in one tree, and the code that formats and draws them treats them the same way. But a document has hundreds of thousands of characters, and an object for each one costs too much memory.1
The same need appears wherever a program has many small objects with few distinct values: the tiles of a game map, the cells of a spreadsheet with the same format, the tokens of a compiler, the trees of a forest in a 3D scene, and the boxed integers and the strings of a language runtime.
The forces are these. The design wants an object for each item, because the uniform treatment is clear and correct. The memory budget allows few objects. And most of the state of each object is the same as in many others.
Solution
Split the state of the object in two.1
- Intrinsic state is the same in each context. It is stored in the flyweight, and it does not change. For a character, it is the character code and the shape of the glyph.
- Extrinsic state depends on the context. The flyweight does not store it. The client computes it or stores it, and passes it to each operation. For a character, it is the position on the page and often the font.
Design Patterns names these participants.1
- Flyweight declares the operations that take the extrinsic state as arguments.
- ConcreteFlyweight stores the intrinsic state. It must be shareable.
- UnsharedConcreteFlyweight implements the same interface but is not shared. A row or a column in the document is an example: it has children, so it is not the same in two places.
- FlyweightFactory makes and manages the flyweights. A client asks the factory for a flyweight with a key. The factory returns the existing object for that key, or makes one and keeps it.
- Client keeps references to flyweights, and it computes or stores their extrinsic state.
text: a b r a c a d a b r a (11 references)
| | | | | | | | | | |
v v v v v v v v v v v
factory pool: a b r c d (5 shared Glyph objects)
glyph.draw(column) the column is extrinsic; the client passes it
The examples draw the word "abracadabra". It has 11 characters and 5 distinct ones, so 11 references point to 5 glyph objects. Each glyph stores its character and its width. The loop computes the column of each glyph from the widths of the glyphs before it, and passes the column to draw.
A flyweight must not change
A flyweight is shared, so a change to it is a change in each place that uses it. A program that stores extrinsic state in a flyweight changes every use at once. Here the program wants to mark the first letter in red:
This code runs but gives a wrong answer on purpose.
class Glyph:
def __init__(self, char):
self.char = char
self.colour = "black" # extrinsic state, stored in the shared object
pool = {}
def glyph(char):
return pool.setdefault(char, Glyph(char))
line = [glyph(c) for c in "abracadabra"]
line[0].colour = "red" # mark the first letter only
print(" ".join(f"{g.char}:{g.colour}" for g in line))
a:red b:black r:black a:red c:black a:red d:black a:red b:black r:black a:red
Each a is red, because there is one a. The fix is to keep the colour out of the glyph. The client stores it for each position, as it does for the column, or a style object for a run of text holds it. A flyweight type that is immutable, such as a frozen dataclass, a Java record, a const C++ object or a Rust value behind Rc, makes the bug impossible to write.
The client must not depend on identity
Design Patterns lists, as a condition for the pattern, that the application does not depend on object identity.1 Two equal values that come from the factory are one object. Two equal values that come from somewhere else may not be. Code that compares with an identity test then gives a result that depends on how the value was made.
Language runtimes are the most common place where this bites, because they use the pattern for boxed numbers and strings. In Java, Integer.valueOf always caches the values from -128 to 127, and it may cache others.3 The Java Language Specification requires that the boxing of an int in that range gives the same object each time.4 Each string literal refers to an interned string, and String.intern returns the string from a pool that the class String keeps.56 The == operator on two references tests identity, not value:
This code runs but gives a wrong answer on purpose.
public class Main {
public static void main(String[] args) {
Integer a = 127, b = 127;
Integer c = 128, d = 128;
System.out.println("127 == 127: " + (a == b));
System.out.println("128 == 128: " + (c == d));
System.out.println("128 equals 128: " + c.equals(d));
String literal = "glyph";
String built = new StringBuilder("gly").append("ph").toString();
System.out.println("built == literal: " + (built == literal));
System.out.println("built.intern() == literal: " + (built.intern() == literal));
}
}
127 == 127: true
128 == 128: false
128 equals 128: true
built == literal: false
built.intern() == literal: true
The specification allows a runtime to cache more values, so the result for 128 can differ between runtimes.34 The fix is equals for objects, or the primitive int.
CPython does the same for small integers. It keeps an array of integer objects for each value from -5 to 256, and the documentation calls this an implementation detail.7 The language reference allows it: for an immutable type, an operation that computes a value may return any existing object with the same type and value.9 So is, which tests identity, gives different answers for equal integers:10
This code runs but gives a wrong answer on purpose.
a, b = int("256"), int("256")
c, d = int("257"), int("257")
print("256 is 256:", a is b)
print("257 is 257:", c is d)
print("257 == 257:", c == d)
256 is 256: True
257 is 257: False
257 == 257: True
The fix is ==. Python's sys.intern interns a string on request.8 .NET's String.Intern returns the one string with a given value from the intern pool. Its documentation warns that this memory is not likely to be released until the runtime terminates.12
Interning as a library
Go's package unique is a flyweight factory in the standard library. It canonicalizes, or interns, comparable values. unique.Make returns a Handle, and two handles are equal if and only if the values used to make them are equal.11 A comparison of two handles is a comparison of two pointers, which costs less than a comparison of two long strings:
package main
import (
"fmt"
"strings"
"unique"
)
func main() {
built := unique.Make(strings.Repeat("ab", 3)) // made at run time
literal := unique.Make("ababab")
other := unique.Make("abab")
fmt.Println("built == literal:", built == literal)
fmt.Println("built == other:", built == other)
fmt.Println("value:", built.Value())
}
built == literal: true
built == other: false
value: ababab
Here the handle is the identity that the program compares, and the factory makes it safe to depend on. In Rust, Rc::ptr_eq tests whether two Rc pointers point to the same value, so a client can test for a shared flyweight on purpose and not by accident.13
Example
Each example file builds a flyweight factory, draws "abracadabra" with it, and prints the count of characters, the count of glyph objects and an identity test on the first and last a.
| Language | Factory | Immutability |
|---|---|---|
| Python | a function with functools.cache |
a frozen dataclass with slots |
| JavaScript | a Map in a class |
Object.freeze |
| TypeScript | a static method, a private constructor | readonly fields |
| Java | HashMap.computeIfAbsent |
a record |
| C# | Dictionary.TryGetValue |
a positional record |
| Go | a map of pointers | unexported fields |
| Rust | HashMap::entry with Rc<Glyph> |
Rc gives out only shared references |
| C++ | a std::map of std::unique_ptr<const Glyph> |
const members |
from dataclasses import dataclass
from functools import cache
WIDTHS = {"i": 1, "l": 1, "r": 1, "m": 3, "w": 3} # all other letters are 2 units wide
@dataclass(frozen=True, slots=True)
class Glyph:
"""A flyweight. It holds only the intrinsic state: the character and its width."""
char: str
width: int
def draw(self, column: int) -> str:
# the column is extrinsic state: the caller passes it in
return f"{self.char}@{column}"
@cache
def glyph(char: str) -> Glyph:
"""The flyweight factory: one Glyph for each character."""
return Glyph(char, WIDTHS.get(char, 2))
text = "abracadabra"
line = [glyph(char) for char in text]
column = 0
drawn = []
for g in line:
drawn.append(g.draw(column))
column += g.width
print(" ".join(drawn))
print(f"characters: {len(line)}, glyph objects: {glyph.cache_info().currsize}")
print("first and last a are one object:", line[0] is line[-1])
a@0 b@2 r@4 a@5 c@7 a@9 d@11 a@13 b@15 r@17 a@18
characters: 11, glyph objects: 5
first and last a are one object: True
- Verdict: stdlib.
functools.cacheturns a constructor call into a flyweight factory. It keeps one result for each argument. - The glyph is a frozen dataclass, so no caller can change a shared glyph.
slots=Trueremoves the per-object__dict__, which matters when there are many small objects. - The column is extrinsic. The loop computes it from the widths and passes it to
draw. A glyph that stored its own column could not be shared. sys.interndoes the same job for strings. CPython also keeps one object for each small integer from -5 to 256. The node page shows whyismust not be used to compare such values.
#include <iostream>
#include <map>
#include <memory>
#include <string>
#include <vector>
// A flyweight holds only the intrinsic state: the character and its width.
class Glyph {
public:
Glyph(char symbol, int width) : symbol_(symbol), width_(width) {}
int width() const { return width_; }
// the column is extrinsic state: the caller passes it in
std::string draw(int column) const { return std::string(1, symbol_) + "@" + std::to_string(column); }
private:
const char symbol_;
const int width_;
};
// The flyweight factory: one Glyph for each character. It owns the glyphs.
class GlyphFactory {
public:
const Glyph& get(char symbol) {
auto& slot = glyphs_[symbol];
if (!slot) {
int width = (symbol == 'i' || symbol == 'l' || symbol == 'r') ? 1 : (symbol == 'm' || symbol == 'w') ? 3 : 2;
slot = std::make_unique<const Glyph>(symbol, width);
}
return *slot;
}
std::size_t size() const { return glyphs_.size(); }
private:
std::map<char, std::unique_ptr<const Glyph>> glyphs_;
};
int main() {
GlyphFactory factory;
std::vector<const Glyph*> line;
for (char symbol : std::string("abracadabra")) {
line.push_back(&factory.get(symbol));
}
int column = 0;
std::string drawn;
for (const Glyph* glyph : line) {
drawn += (drawn.empty() ? "" : " ") + glyph->draw(column);
column += glyph->width();
}
std::cout << drawn << '\n';
std::cout << "characters: " << line.size() << ", glyph objects: " << factory.size() << '\n';
std::cout << std::boolalpha << "first and last a are one object: " << (line.front() == line.back()) << '\n';
}
a@0 b@2 r@4 a@5 c@7 a@9 d@11 a@13 b@15 r@17 a@18
characters: 11, glyph objects: 5
first and last a are one object: true
- Verdict: idiom. The factory owns each glyph through a
std::unique_ptr<const Glyph>, and clients hold plainconst Glyph*pointers that do not own. - The pointers stay valid while the factory lives. A
std::mapdoes not move its nodes when it grows, and theunique_ptrkeeps each glyph at one address in any case. constmembers and aconst Glyphtype stop a change to a shared glyph at compile time.- The two pointers are compared with
==. The program prints the result of the test and not the addresses, which change from run to run.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
/** A flyweight holds only the intrinsic state: the character and its width. */
record Glyph(char symbol, int width) {
String draw(int column) {
return symbol + "@" + column; // the column is extrinsic: the caller passes it in
}
}
/** The flyweight factory: one Glyph for each character. */
static final class GlyphFactory {
private static final Map<Character, Integer> WIDTHS = Map.of('i', 1, 'l', 1, 'r', 1, 'm', 3, 'w', 3);
private final Map<Character, Glyph> glyphs = new HashMap<>();
Glyph get(char symbol) {
return glyphs.computeIfAbsent(symbol, s -> new Glyph(s, WIDTHS.getOrDefault(s, 2)));
}
int size() {
return glyphs.size();
}
}
public static void main(String[] args) {
GlyphFactory factory = new GlyphFactory();
List<Glyph> line = new ArrayList<>();
for (char symbol : "abracadabra".toCharArray()) {
line.add(factory.get(symbol));
}
int column = 0;
List<String> drawn = new ArrayList<>();
for (Glyph glyph : line) {
drawn.add(glyph.draw(column));
column += glyph.width();
}
System.out.println(String.join(" ", drawn));
System.out.println("characters: " + line.size() + ", glyph objects: " + factory.size());
System.out.println("first and last a are one object: " + (line.getFirst() == line.getLast()));
}
}
a@0 b@2 r@4 a@5 c@7 a@9 d@11 a@13 b@15 r@17 a@18
characters: 11, glyph objects: 5
first and last a are one object: true
- Verdict: idiom. A
recordfor the shared state andMap.computeIfAbsentfor the factory. The fields of a record arefinal, so a shared glyph cannot change. - The JDK uses the pattern for boxed values.
Integer.valueOfreturns cached objects for the values from -128 to 127, and string literals are interned. The node page shows the bug that this causes with==. Map<Character, Glyph>boxes each key.Character.valueOfcaches the characters from'\u0000'to'\u007F', so these keys are flyweights as well.- The factory is not thread-safe. A
ConcurrentHashMapwith the samecomputeIfAbsentcall makes it safe to share between threads.
using System;
using System.Collections.Generic;
using System.Linq;
var factory = new GlyphFactory();
List<Glyph> line = "abracadabra".Select(factory.Get).ToList();
int column = 0;
var drawn = new List<string>();
foreach (Glyph glyph in line)
{
drawn.Add(glyph.Draw(column));
column += glyph.Width;
}
Console.WriteLine(string.Join(" ", drawn));
Console.WriteLine($"characters: {line.Count}, glyph objects: {factory.Count}");
Console.WriteLine($"first and last a are one object: {ReferenceEquals(line[0], line[^1])}");
// A flyweight holds only the intrinsic state: the character and its width.
sealed record Glyph(char Symbol, int Width)
{
// the column is extrinsic: the caller passes it in
public string Draw(int column) => $"{Symbol}@{column}";
}
// The flyweight factory: one Glyph for each character.
sealed class GlyphFactory
{
private static readonly Dictionary<char, int> Widths = new() { ['i'] = 1, ['l'] = 1, ['r'] = 1, ['m'] = 3, ['w'] = 3 };
private readonly Dictionary<char, Glyph> glyphs = [];
public int Count => glyphs.Count;
public Glyph Get(char symbol)
{
if (!glyphs.TryGetValue(symbol, out Glyph? glyph))
{
glyph = new Glyph(symbol, Widths.GetValueOrDefault(symbol, 2));
glyphs[symbol] = glyph;
}
return glyph;
}
}
a@0 b@2 r@4 a@5 c@7 a@9 d@11 a@13 b@15 r@17 a@18
characters: 11, glyph objects: 5
first and last a are one object: True
- Verdict: idiom. A
Dictionaryfrom the key to the shared object, and a positionalrecordwith init-only properties, so a shared glyph cannot change. - The test uses
ReferenceEquals. A record's==compares the values of its properties, so==would be true for two separate glyphs with the same character. string.Internreturns the one string in the intern pool with a given value. The documentation says that this memory is not likely to be released until the runtime terminates, so interning strings from input can hold memory for the life of the process.- A
structis the other way to avoid many small objects. A value type has no object header and no reference, and aList<T>of them stores the values inline.
const WIDTHS = { i: 1, l: 1, r: 1, m: 3, w: 3 }; // all other letters are 2 units wide
// A flyweight holds only the intrinsic state: the character and its width.
class Glyph {
constructor(char) {
this.char = char;
this.width = WIDTHS[char] ?? 2;
Object.freeze(this); // no caller can change a shared glyph
}
draw(column) {
return `${this.char}@${column}`; // the column is extrinsic: the caller passes it in
}
}
// The flyweight factory: one Glyph for each character.
class GlyphFactory {
#glyphs = new Map();
get(char) {
let glyph = this.#glyphs.get(char);
if (glyph === undefined) {
glyph = new Glyph(char);
this.#glyphs.set(char, glyph);
}
return glyph;
}
get size() {
return this.#glyphs.size;
}
}
const factory = new GlyphFactory();
const line = [..."abracadabra"].map((char) => factory.get(char));
let column = 0;
const drawn = [];
for (const glyph of line) {
drawn.push(glyph.draw(column));
column += glyph.width;
}
console.log(drawn.join(" "));
console.log(`characters: ${line.length}, glyph objects: ${factory.size}`);
console.log("first and last a are one object:", line[0] === line.at(-1));
a@0 b@2 r@4 a@5 c@7 a@9 d@11 a@13 b@15 r@17 a@18
characters: 11, glyph objects: 5
first and last a are one object: true
- Verdict: idiom. A
Mapfrom the key to the shared object, andObject.freezeon each object that it hands out. Object.freezeis shallow. A glyph with an array field would need a frozen array too.- JavaScript strings are primitive values, and
===compares them by value. A program never needs to intern a string to compare it fast in its own code. - Methods on a class live once on its prototype object, not on each instance. This is sharing of the same kind, built into the language.
const WIDTHS: Readonly<Record<string, number>> = { i: 1, l: 1, r: 1, m: 3, w: 3 }; // others are 2
// A flyweight holds only the intrinsic state. Only Glyph.of can make one.
class Glyph {
static readonly #pool = new Map<string, Glyph>();
static of(char: string): Glyph {
let glyph = Glyph.#pool.get(char);
if (glyph === undefined) {
glyph = new Glyph(char, WIDTHS[char] ?? 2);
Glyph.#pool.set(char, glyph);
}
return glyph;
}
static get count(): number {
return Glyph.#pool.size;
}
readonly char: string;
readonly width: number;
private constructor(char: string, width: number) {
this.char = char;
this.width = width;
}
draw(column: number): string {
return `${this.char}@${column}`; // the column is extrinsic: the caller passes it in
}
}
const line: readonly Glyph[] = [..."abracadabra"].map(Glyph.of);
let column = 0;
const drawn: string[] = [];
for (const glyph of line) {
drawn.push(glyph.draw(column));
column += glyph.width;
}
console.log(drawn.join(" "));
console.log(`characters: ${line.length}, glyph objects: ${Glyph.count}`);
console.log("first and last a are one object:", line[0] === line.at(-1));
a@0 b@2 r@4 a@5 c@7 a@9 d@11 a@13 b@15 r@17 a@18
characters: 11, glyph objects: 5
first and last a are one object: true
- Verdict: idiom. A static factory method and a
privateconstructor, so that code outside the class cannot make a second glyph for the same character. readonlyfields stop a change to a shared glyph at compile time. They do not freeze the object at run time.private constructoris a compile-time check only. The#poolfield is private at run time as well.
package main
import (
"fmt"
"strings"
)
var widths = map[rune]int{'i': 1, 'l': 1, 'r': 1, 'm': 3, 'w': 3} // all other letters are 2 units wide
// Glyph is a flyweight. It holds only the intrinsic state: the character and its width.
type Glyph struct {
char rune
width int
}
// Draw takes the column as extrinsic state.
func (g *Glyph) Draw(column int) string { return fmt.Sprintf("%c@%d", g.char, column) }
// GlyphFactory hands out one *Glyph for each character.
type GlyphFactory struct{ glyphs map[rune]*Glyph }
func (f *GlyphFactory) Get(char rune) *Glyph {
if g, ok := f.glyphs[char]; ok {
return g
}
width, ok := widths[char]
if !ok {
width = 2
}
g := &Glyph{char: char, width: width}
f.glyphs[char] = g
return g
}
func main() {
factory := &GlyphFactory{glyphs: map[rune]*Glyph{}}
var line []*Glyph
for _, char := range "abracadabra" {
line = append(line, factory.Get(char))
}
column := 0
var drawn []string
for _, g := range line {
drawn = append(drawn, g.Draw(column))
column += g.width
}
fmt.Println(strings.Join(drawn, " "))
fmt.Printf("characters: %d, glyph objects: %d\n", len(line), len(factory.glyphs))
fmt.Println("first and last a are one object:", line[0] == line[len(line)-1])
}
a@0 b@2 r@4 a@5 c@7 a@9 d@11 a@13 b@15 r@17 a@18
characters: 11, glyph objects: 5
first and last a are one object: true
- Verdict: idiom. A map from the key to a pointer, and unexported fields, so code in other packages cannot change a shared glyph.
==on two pointers compares the addresses, so it tests identity.==on twoGlyphvalues compares the fields.- Package
uniquecanonicalizes comparable values.unique.Makereturns aHandle, and two handles are equal when the values were equal. The node page has an example. - A slice of
Glyphvalues, not pointers, is the other choice for small immutable values. The copies sit in one array, with no pointers and no separate heap objects, and for a struct this small that can cost less memory than the shared form.
use std::collections::HashMap;
use std::rc::Rc;
/// A flyweight holds only the intrinsic state: the character and its width.
struct Glyph {
symbol: char,
width: usize,
}
impl Glyph {
/// The column is extrinsic state: the caller passes it in.
fn draw(&self, column: usize) -> String {
format!("{}@{}", self.symbol, column)
}
}
/// The flyweight factory: one shared Glyph for each character.
#[derive(Default)]
struct GlyphFactory {
glyphs: HashMap<char, Rc<Glyph>>,
}
impl GlyphFactory {
fn get(&mut self, symbol: char) -> Rc<Glyph> {
let glyph = self.glyphs.entry(symbol).or_insert_with(|| {
let width = match symbol {
'i' | 'l' | 'r' => 1,
'm' | 'w' => 3,
_ => 2,
};
Rc::new(Glyph { symbol, width })
});
Rc::clone(glyph)
}
}
fn main() {
let mut factory = GlyphFactory::default();
let line: Vec<Rc<Glyph>> = "abracadabra".chars().map(|c| factory.get(c)).collect();
let mut column = 0;
let mut drawn = Vec::new();
for glyph in &line {
drawn.push(glyph.draw(column));
column += glyph.width;
}
println!("{}", drawn.join(" "));
println!("characters: {}, glyph objects: {}", line.len(), factory.glyphs.len());
println!(
"first and last a are one object: {}",
Rc::ptr_eq(&line[0], &line[line.len() - 1])
);
println!("references to the a glyph: {}", Rc::strong_count(&line[0]));
}
a@0 b@2 r@4 a@5 c@7 a@9 d@11 a@13 b@15 r@17 a@18
characters: 11, glyph objects: 5
first and last a are one object: true
references to the a glyph: 6
- Verdict: idiom. A
HashMapofRc<Glyph>, andRc::cloneto hand out one more reference to the same glyph. Rcgives shared ownership of an immutable value. The type system stops a change to a shared glyph:Rc<T>gives out only&T, so a call that needs&mut Glyphdoes not compile.Rc::ptr_eqcompares the two pointers, not the values.==onRc<T>compares the values and needsT: PartialEq.- The count of 6 references to the
aglyph is 5 from the line and 1 from the factory.Arcis the thread-safe form.
Consequences
The benefit is memory. Design Patterns says that the savings depend on three things: how far the count of instances falls through sharing, how much intrinsic state each object has, and whether the extrinsic state is computed or stored.1 The savings are largest when the extrinsic state is computed, as the column is in the examples, so that the program stores almost nothing for each use. Fewer objects also mean less work for a garbage collector and better use of the cache. Shared objects can be compared by identity, which is cheap, once all of them come from the factory.
The costs are these. Design Patterns notes the run-time cost to transfer, find or compute the extrinsic state.1 Each operation takes more arguments, and the code that computes them is in the client. The factory is a global pool: it must be safe for concurrent use when threads share it, and it keeps each flyweight alive unless it uses weak references. A pool that interns values from input, such as user names or log lines, grows without limit. And the design is harder to read, because the state of one logical object is in two places.
A flyweight also cannot know its context. A shared leaf in a tree cannot store a pointer to its parent, because it has many parents. Design Patterns notes that a flyweight leaf in a composite has this limit.1
When not to use it
Do not use it until a measurement shows that the objects cost too much. Design Patterns says that all of its applicability conditions must hold: the program uses many objects, the storage cost is high, most of the state can be made extrinsic, many groups of objects can then be replaced by few shared ones, and the program does not depend on object identity.1
Do not use it for values that are cheap to copy. In Go, Rust, C# and C++, a small struct can be a value type stored inline in an array. An array of 11 small values can cost less than 11 pointers to 5 shared heap objects, and the values need no factory and no pool.
Do not use it for objects that change. A shared mutable object is a shared global variable, and the bug above follows.
Do not intern untrusted input in a pool that never shrinks. The pool becomes a memory leak that an attacker can fill.
Peter Norvig lists Flyweight among the patterns that first-class types make invisible or simpler in a dynamic language.14 In many runtimes, interning and small-integer caches already apply the pattern to the most common values.
Variants and related patterns
Composite. Design Patterns says that the pattern is often combined with Composite to build a hierarchy with shared leaf nodes.1 The editor's characters are shared leaves in a tree of rows and pages. See Composite pattern.
State and Strategy. Design Patterns says that state and strategy objects are often built as flyweights.1 A state object with no fields, or a strategy that is a pure function, can be one shared object for all contexts. See State pattern and Strategy pattern.
Singleton. A singleton is one object for a class. A flyweight factory keeps one object for each key. The factory itself is often a singleton or a module-level value. See Singleton pattern.
Prototype. A prototype makes a copy for each use. A flyweight shares one object for each value. A prototype whose fields are all immutable needs no copy, and it can be shared as a flyweight. See Prototype pattern.
Interning and hash consing. Interning is the flyweight factory for values such as strings and symbols. Hash consing applies it to the nodes of a data structure, so that equal subtrees are one object.
Memoization. functools.cache in the Python example is a memoizing decorator. A flyweight factory is memoization of a constructor.
Known uses
- Java:
Integer.valueOfcaches the values from -128 to 127, and string literals are interned.35 - CPython: one integer object for each value from -5 to 256, and
sys.internfor strings.78 - .NET: the intern pool of
String.Intern.12 - Go: package
uniqueinterns comparable values.11 - InterViews: Calder and Linton describe glyphs as flyweight objects for user interfaces.2
References
- Gamma, Helm, Johnson and Vlissides, Design Patterns, Elements of Reusable Object-Oriented Software, Addison-Wesley, 1994, Chapter 4, Flyweight (Intent, Motivation, Applicability, Participants, Consequences, Implementation, Known Uses, Related Patterns)
- Paul R. Calder and Mark A. Linton, Glyphs, flyweight objects for user interfaces, UIST 1990, title
- Java SE 25 API, java.lang.Integer, method valueOf(int)
- The Java Language Specification, Java SE 25 Edition, 5.1.7 Boxing Conversion
- The Java Language Specification, Java SE 25 Edition, 3.10.5 String Literals
- Java SE 25 API, java.lang.String, method intern
- Python/C API Reference Manual, Integer Objects, Python 3.14, PyLong_FromLong
- The Python Standard Library, sys, Python 3.14, sys.intern
- The Python Language Reference, Data model, Python 3.14, 3.1 Objects, values and types
- The Python Language Reference, Expressions, Python 3.14, Identity comparisons
- Go standard library, package unique, package overview; type Handle; func Make
- .NET API reference, String.Intern, Remarks; Performance considerations
- Rust standard library, std::rc::Rc, method ptr_eq
- Peter Norvig, Design Patterns in Dynamic Programming, Object World, 1996, slide 10, Design Patterns in Dylan or Lisp
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 6KZR0J Edit this page History Report an error Markdown