Skip to content

Bridge Pattern: Split Abstraction from Implementation

Learn the Bridge pattern through a warehouse label system that keeps label types and printer drivers growing independently.

12 min readDesign patternStructural

Decouple an abstraction from its implementation so the two can be extended independently. The abstraction holds a reference to an implementation object and delegates the low-level work to it, replacing a combined inheritance tree with composition across two separate hierarchies.

Bridge is the pattern you reach for when a class hierarchy starts growing in two directions at once. Instead of one inheritance tree that multiplies every variant on one axis by every variant on the other, you split it into two trees and connect them with a reference. One side describes what you want to do; the other side knows how to do it on a specific platform. In this guide you follow a warehouse team whose label printing code hit exactly that wall. You will see the class explosion, the refactoring into two hierarchies, the structure, and runnable code in TypeScript, Python and PHP. In interviews, Bridge often comes up next to Adapter and Strategy, so the FAQ covers how to tell them apart.

The problem

A situation where the obvious design starts to hurt.

Parcelyard runs fulfilment for 40 online shops from two warehouses. Its label service prints three kinds of labels: shipping labels for outgoing parcels, return labels that go inside the box, and pallet labels for freight. The warehouses use four printer languages: ZPL for the Zebra thermal printers, EPL for an older fleet, ESC/POS for small desk printers, and a text preview used by the web dashboard and the test suite.

The first version modelled this with inheritance. There was a Label base class, then ShippingLabel, then ZplShippingLabel, EplShippingLabel, EscPosShippingLabel and PreviewShippingLabel, and the same four again for returns and pallets. That is 3 x 4 = 12 concrete classes.

The pain showed up in two ways. When the second warehouse bought Brother printers, supporting a fifth language meant writing three new classes, one per label type, each repeating the layout logic. When marketing asked for a QR code on return labels, someone had to change four classes, one per printer language, and the EPL version was forgotten for two weeks. Layout decisions and printer command syntax were tangled inside the same classes, so every change on one axis touched every class on the other.

The solution

What the pattern proposes.

Bridge separates the two axes. The label hierarchy keeps the layout: what goes on a shipping label, where the recipient name sits, how big the barcode is. The printer hierarchy keeps the command syntax: how ZPL encodes a text field, how the preview renders a barcode. They talk through a small interface, LabelPrinter, with four primitives: begin, text, barcode and finish.

Every Label receives a LabelPrinter in its constructor and calls only those primitives. ShippingLabel never mentions ZPL; ZplPrinter never knows what a return label is. The reference from Label to LabelPrinter is the bridge.

Now Parcelyard has 3 label classes plus 4 printer classes, 7 in total instead of 12. Adding the Brother driver means writing one class that implements LabelPrinter, and every existing label works on it immediately. Adding a QR code to return labels means editing one class, ReturnLabel, plus adding a qrCode primitive to the interface once. The two hierarchies grow additively instead of multiplicatively.

An everyday analogy

The same idea, outside software.

Think of a theatre script and the touring companies that perform it. The script decides the scenes, the lines and the order of events. Each company decides how to stage it: one has a revolving stage, another a bare black box, another performs outdoors with portable lights. A new play can be performed by any company that knows the basic stage directions, and a new company can perform any existing play. Nobody writes a separate version of every play for every venue; the stage directions are the shared vocabulary between the two.

Structure

The pieces and how they relate.

Label types (abstraction) hold a reference to a LabelPrinter (implementation); each side has its own subclasses.LabelService calls Label (render()). LabelService creates ZplPrinter (chooses driver). ShippingLabel inherits from Label. ReturnLabel inherits from Label. Label has a LabelPrinter (bridge). ZplPrinter implements LabelPrinter. TextPreviewPrinter implements LabelPrinter.LabelServicepicks label +printer«abstract»Labelprinter:LabelPrinter…ShippingLabelrender()ReturnLabelrender()«interface»LabelPrinterbegin, text,barcode, finishZplPrinteremits ZPL commandsTextPreviewPrinteremits readable text3 x 4 = 12 becomes 3 + 4 = 7each axis grows on its ownrender()chooses driverbridge
Label types (abstraction) hold a reference to a LabelPrinter (implementation); each side has its own subclasses.

Participants

Abstraction (Label)
Defines the high-level operation, render(), and holds a reference to a LabelPrinter. It never formats printer commands itself; it describes a layout in terms of the implementation's primitives.
Refined Abstraction (ShippingLabel, ReturnLabel)
Concrete label types. Each decides which fields appear, their positions and sizes, and the label dimensions, then calls begin, text, barcode and finish on whatever printer it was given.
Implementation (LabelPrinter)
The interface shared by all printer drivers. It exposes low-level primitives, not label concepts, so it stays small and stable while label types change.
Concrete Implementation (ZplPrinter, TextPreviewPrinter)
Translate the primitives into a specific output: ZPL commands for Zebra printers, or a human-readable preview for the dashboard and tests.
Client (LabelService)
Picks a printer for the warehouse station, builds the right label with that printer, and calls render(). It is usually the only place that knows both concrete sides.

Pseudocode

The solution to the scenario, language-neutral.

interface LabelPrinter
    method begin(widthMm, heightMm)
    method text(x, y, sizeMm, value)
    method barcode(x, y, data)
    method finish(): string

class ZplPrinter implements LabelPrinter
    field lines
    method begin(w, h)
        lines = ["^XA", "^PW" + w * 8, "^LL" + h * 8]
    method text(x, y, size, value)
        lines.add(field-origin(x, y) + font(size) + value)
    method barcode(x, y, data)
        lines.add(field-origin(x, y) + code128(data))
    method finish()
        lines.add("^XZ")
        return join(lines)

class TextPreviewPrinter implements LabelPrinter
    // same four methods, readable text instead of ZPL

abstract class Label
    field printer: LabelPrinter
    constructor(printer)
        this.printer = printer
    abstract method render(): string

class ShippingLabel extends Label
    method render()
        printer.begin(100, 150)
        printer.text(5, 5, 6, recipient)
        printer.text(5, 15, 4, address)
        printer.barcode(5, 40, orderId)
        return printer.finish()

class ReturnLabel extends Label
    method render()
        printer.begin(100, 50)
        printer.text(5, 5, 5, "RETURN " + rmaCode)
        printer.text(5, 14, 3, "Reason: " + reason)
        printer.barcode(5, 22, rmaCode)
        return printer.finish()

// client
printer = new ZplPrinter()
label = new ShippingLabel(printer, "PY-40213", "Ana Ruiz", "12 Harbour St")
send(label.render())

The code

The same solution in TypeScript, Python and PHP.

interface LabelPrinter {
  begin(widthMm: number, heightMm: number): void;
  text(x: number, y: number, sizeMm: number, value: string): void;
  barcode(x: number, y: number, data: string): void;
  finish(): string;
}

const DOTS_PER_MM = 8; // 203 dpi thermal printers

class ZplPrinter implements LabelPrinter {
  private lines: string[] = [];

  begin(widthMm: number, heightMm: number): void {
    this.lines = ["^XA", `^PW${widthMm * DOTS_PER_MM}`, `^LL${heightMm * DOTS_PER_MM}`];
  }

  text(x: number, y: number, sizeMm: number, value: string): void {
    const h = sizeMm * DOTS_PER_MM;
    this.lines.push(`^FO${x * DOTS_PER_MM},${y * DOTS_PER_MM}^A0N,${h},${h}^FD${value}^FS`);
  }

  barcode(x: number, y: number, data: string): void {
    this.lines.push(`^FO${x * DOTS_PER_MM},${y * DOTS_PER_MM}^BCN,80,Y,N,N^FD${data}^FS`);
  }

  finish(): string {
    this.lines.push("^XZ");
    return this.lines.join("\n");
  }
}

class TextPreviewPrinter implements LabelPrinter {
  private lines: string[] = [];

  begin(widthMm: number, heightMm: number): void {
    this.lines = [`[label ${widthMm}x${heightMm} mm]`];
  }

  text(x: number, y: number, sizeMm: number, value: string): void {
    this.lines.push(`  text (${x},${y}) ${sizeMm}mm: ${value}`);
  }

  barcode(x: number, y: number, data: string): void {
    this.lines.push(`  barcode (${x},${y}): ${data}`);
  }

  finish(): string {
    return this.lines.join("\n");
  }
}

abstract class Label {
  constructor(protected printer: LabelPrinter) {}
  abstract render(): string;
}

class ShippingLabel extends Label {
  constructor(
    printer: LabelPrinter,
    private orderId: string,
    private recipient: string,
    private address: string,
  ) {
    super(printer);
  }

  render(): string {
    this.printer.begin(100, 150);
    this.printer.text(5, 5, 6, this.recipient);
    this.printer.text(5, 15, 4, this.address);
    this.printer.barcode(5, 40, this.orderId);
    return this.printer.finish();
  }
}

class ReturnLabel extends Label {
  constructor(printer: LabelPrinter, private rmaCode: string, private reason: string) {
    super(printer);
  }

  render(): string {
    this.printer.begin(100, 50);
    this.printer.text(5, 5, 5, `RETURN ${this.rmaCode}`);
    this.printer.text(5, 14, 3, `Reason: ${this.reason}`);
    this.printer.barcode(5, 22, this.rmaCode);
    return this.printer.finish();
  }
}

// Client: any label works with any printer.
const zpl = new ZplPrinter();
const preview = new TextPreviewPrinter();

console.log(new ShippingLabel(zpl, "PY-40213", "Ana Ruiz", "12 Harbour St, Leeds LS1 4AB").render());
console.log(new ReturnLabel(preview, "RMA-7781", "wrong size").render());

When to use it

Situations where it pays off.

  • A class hierarchy multiplies along two independent dimensions, such as label type times printer language, report type times storage backend, or widget times rendering engine.

    Bridge turns an N x M set of subclasses into N + M classes. Each new variant on one axis is written once and works with everything on the other axis.

  • You need to switch the implementation at runtime, for example sending the same label to a thermal printer at the packing station and to a preview in the dashboard.

    Because the abstraction holds the implementation by reference, swapping it is just passing a different object. Inheritance fixes the choice at compile time.

  • Platform-specific code keeps leaking into business logic, and changes to one force edits in the other.

    Bridge draws a hard line: the abstraction only speaks in primitives defined by the implementation interface, so platform details stay in one place per platform.

  • You want to test high-level logic without the real platform, such as checking label layouts without a physical printer.

    A lightweight implementation, like Parcelyard's text preview, plugs into the same abstraction and gives you deterministic output to assert against.

How to implement it

Steps to introduce it in existing code.

  1. Identify the two dimensions in your hierarchy. Ask which part describes what the object does for the user and which part deals with a platform, vendor or backend. In Parcelyard's case: label layout versus printer language.

  2. Design the implementation interface from what the abstraction actually needs. List the operations every label uses and reduce them to primitives, such as begin, text, barcode and finish. Keep it free of abstraction concepts like 'shipping'.

  3. Write one concrete implementation per platform. Move the command syntax that used to live in the combined subclasses into these classes.

  4. Create the abstraction class with a field of the implementation interface type, set through the constructor. Express its high-level operation only in terms of that interface.

  5. Turn each former variant on the abstraction side into a refined abstraction that extends the base class and contains only layout logic.

  6. Update the client so it creates an implementation, passes it into the abstraction, and then works only with the abstraction. Delete the old combined subclasses once all callers have moved.

  7. When a new primitive is needed, add it to the interface and to every implementation once, then use it from whichever abstractions need it.

Pros and cons

What you gain and what you pay.

Pros

  • Removes the N x M class explosion: two hierarchies of N and M classes replace one tree of N x M.
  • Each side follows the open/closed principle: new label types and new printers are added without touching existing classes on the other side.
  • Implementations can be swapped at runtime or injected in tests, because the link is composition rather than inheritance.
  • Platform-specific details are isolated, so a printer firmware quirk is fixed in exactly one class.
  • High-level code becomes easier to read because it only expresses intent through a small set of primitives.

Cons

  • Adds indirection and extra types, which is not worth it when only one dimension really varies.
  • Designing a good implementation interface is hard: too narrow and some platforms cannot express features, too wide and every implementation must support rarely used operations.
  • Adding a primitive to the implementation interface forces a change in every concrete implementation.
  • Features that only one platform supports, like a printer-specific graphic format, fit awkwardly and may need capability checks or fallbacks.

Relations with other guides

Patterns it's often confused or combined with.

Common questions

Short answers to the usual doubts.

What is the difference between Bridge and Adapter?

Timing and intent. Adapter is a retrofit: you have a class with the wrong interface and wrap it so existing code can use it. Bridge is a design decision made before the hierarchies grow, so abstraction and implementation can evolve independently. If an interviewer asks, say Adapter makes unrelated things work together after they exist, while Bridge keeps two dimensions apart from the start.

Isn't Bridge just Strategy with a different name?

The code shape is similar: an object holds an interface reference and delegates to it. The difference is scope. Strategy swaps one behaviour inside a single context class. In Bridge the abstraction side is itself a hierarchy, like ShippingLabel and ReturnLabel, and the implementation side provides the platform primitives that all those subclasses build on.

How do I spot that I need Bridge in an existing codebase?

Look for class names that combine two words from different axes, such as ZplShippingLabel and EplReturnLabel, and for changes that require editing the same logic in several sibling classes. If adding one new variant forces you to write several classes, you have a multiplying hierarchy that Bridge can flatten.

Who decides which implementation the abstraction uses?

Usually the client or a composition root, through constructor injection as in the Parcelyard example. You can also use a factory that maps a warehouse station to its printer driver. The abstraction should not pick its own implementation, or you lose the independence Bridge is meant to give.

When is Bridge overkill?

When only one dimension actually varies, or the second dimension has a single implementation with no realistic prospect of a second. Then the extra interface is speculative generality. Start with a plain class and introduce the bridge when the second variant appears.

Next guide3 of 7 · Structural patternsComposite Pattern: Treat Single Items and Groups Through One InterfaceRead the next one