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.

Intermediate 2 min readLesson 13 of 24

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.

bridgeShaperenderer: RendererCircleSquare«interface» RendererdrawCircle · drawRectSvgRendererCanvasRenderer

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();

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 stateExtrinsic state
WhatShared, context-independent, immutableUnique per use
Tree exampleMesh, texture, species namePosition, scale, health
Character exampleGlyph shape, fontPosition in the document
Stored inThe 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 memory

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.
Key takeaways
  • 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.