Bridge & Flyweight
Bridge separates an abstraction from its implementation so both can vary independently; Flyweight shares intrinsic state to support huge numbers of fine-grained objects.
Two structural patterns that come up less often than Adapter or Decorator, but solve distinctive problems.
Bridge
Intent: decouple an abstraction from its implementation so the two can vary independently.
The problem: two dimensions of variation
Shapes (circle, square) × renderers (SVG, Canvas, PDF). With inheritance alone you get SvgCircle, CanvasCircle, PdfCircle, SvgSquare… M × N classes. Add a shape and you write N new classes.
The bridge splits the hierarchy in two and connects them by composition: the abstraction has an implementation.
M + N classes instead of M × N.
interface Renderer { // implementation side
void drawCircle(double x, double y, double r);
void drawRect(double x, double y, double w, double h);
}
class SvgRenderer implements Renderer {
public void drawCircle(double x, double y, double r) {
System.out.printf("<circle cx='%f' cy='%f' r='%f'/>%n", x, y, r);
}
public void drawRect(double x, double y, double w, double h) { /* <rect .../> */ }
}
abstract class Shape { // abstraction side
protected final Renderer renderer; // the bridge
Shape(Renderer renderer) { this.renderer = renderer; }
abstract void draw();
}
class Circle extends Shape {
private final double x, y, r;
Circle(Renderer rd, double x, double y, double r) { super(rd); this.x = x; this.y = y; this.r = r; }
void draw() { renderer.drawCircle(x, y, r); }
}
new Circle(new SvgRenderer(), 10, 10, 5).draw();
new Circle(new CanvasRenderer(ctx), 10, 10, 5).draw();class Renderer(Protocol):
def draw_circle(self, x, y, r): ...
class SvgRenderer:
def draw_circle(self, x, y, r):
print(f'<circle cx="{x}" cy="{y}" r="{r}"/>')
class Shape:
def __init__(self, renderer: Renderer):
self.renderer = renderer # the bridge
class Circle(Shape):
def __init__(self, renderer, x, y, r):
super().__init__(renderer)
self.x, self.y, self.r = x, y, r
def draw(self):
self.renderer.draw_circle(self.x, self.y, self.r)
Circle(SvgRenderer(), 10, 10, 5).draw()interface Renderer { drawCircle(x: number, y: number, r: number): void; }
class SvgRenderer implements Renderer {
drawCircle(x: number, y: number, r: number) { console.log(`<circle cx="${x}" cy="${y}" r="${r}"/>`); }
}
abstract class Shape {
constructor(protected renderer: Renderer) {} // the bridge
abstract draw(): void;
}
class Circle extends Shape {
constructor(r: Renderer, private x: number, private y: number, private radius: number) { super(r); }
draw() { this.renderer.drawCircle(this.x, this.y, this.radius); }
}Real examples: JDBC (your code uses Connection/Statement; drivers implement them for each database), SLF4J (logging API vs backends), GUI toolkits over native windowing systems, device drivers.
Flyweight
Intent: use sharing to support large numbers of fine-grained objects efficiently.
The problem
A text editor with a million characters, a game with 100,000 trees, a map with millions of markers. If each object stores everything (font, texture, mesh, colour), memory explodes. But most of that data is identical across objects.
Split each object's state:
| Intrinsic state | Extrinsic state | |
|---|---|---|
| What | Shared, context-independent, immutable | Unique per use |
| Tree example | Mesh, texture, species name | Position, scale, health |
| Character example | Glyph shape, font | Position in the document |
| Stored in | The flyweight (shared) | The context object or passed in by the caller |
// Flyweight: immutable, shared
record TreeType(String species, Mesh mesh, Texture texture) {
void draw(Canvas c, int x, int y) { c.draw(mesh, texture, x, y); }
}
// Factory caches flyweights
final class TreeTypes {
private static final Map<String, TreeType> cache = new ConcurrentHashMap<>();
static TreeType of(String species) {
return cache.computeIfAbsent(species,
s -> new TreeType(s, Mesh.load(s), Texture.load(s))); // loaded once per species
}
}
// Context: small per-instance object
record Tree(int x, int y, TreeType type) {
void draw(Canvas c) { type.draw(c, x, y); }
}
List<Tree> forest = new ArrayList<>();
for (int i = 0; i < 100_000; i++)
forest.add(new Tree(rnd.nextInt(5000), rnd.nextInt(5000), TreeTypes.of(i % 2 == 0 ? "oak" : "pine")));
// 100,000 small Tree objects, but only 2 meshes and 2 textures in memoryfrom dataclasses import dataclass
from functools import cache
@dataclass(frozen=True)
class TreeType: # flyweight
species: str
mesh: bytes
texture: bytes
@cache # the factory: one instance per species
def tree_type(species: str) -> TreeType:
return TreeType(species, load_mesh(species), load_texture(species))
@dataclass(slots=True) # slots: small per-instance footprint
class Tree:
x: int
y: int
type: TreeType
forest = [Tree(random.randrange(5000), random.randrange(5000), tree_type("oak")) for _ in range(100_000)]class TreeType { // flyweight (treat as immutable)
constructor(readonly species: string, readonly mesh: Mesh, readonly texture: Texture) {}
}
const types = new Map<string, TreeType>();
function treeType(species: string): TreeType {
let t = types.get(species);
if (!t) types.set(species, (t = new TreeType(species, loadMesh(species), loadTexture(species))));
return t;
}
interface Tree { x: number; y: number; type: TreeType }
const forest: Tree[] = Array.from({ length: 100_000 }, () => ({
x: Math.random() * 5000, y: Math.random() * 5000, type: treeType("oak"),
}));Flyweights you already use
- String interning: Java string literals and
String.intern(); Python interns short strings and identifiers. - Integer caches:
Integer.valueOf(-128..127)returns shared instances (why==on boxed Integers "works" for small numbers and fails for large ones); CPython caches small ints −5..256. - Enums and
Boolean.TRUE/FALSE. - Game engines: GPU instancing draws many copies of one mesh with different transforms.
- Bridge: split two dimensions of variation into two hierarchies joined by composition (M + N, not M × N).
- JDBC and logging facades are bridges between APIs and implementations.
- Flyweight: share immutable intrinsic state; keep extrinsic state per instance.
- String interning, integer caches and GPU instancing are flyweights.