Bridge Pattern

Split one class family that varies in two directions into two hierarchies joined by composition, so each side can grow without multiplying the other.

Overview

The problem it solves A hierarchy starts to vary in two directions at once. Shapes come in circles and squares; they can be drawn as vectors or as pixels. With inheritance alone you end up with VectorCircle, RasterCircle, VectorSquare, RasterSquare, and every new shape or renderer multiplies the list. The Bridge pattern cuts the family in two. One hierarchy holds what the object is (the abstraction: shapes). The other holds how the work is done (the implementor: renderers). The abstraction holds a reference to an implementor and delegates the low-level steps to it.

The pattern is a structural pattern from the Gang of Four book (Gamma, Helm, Johnson and Vlissides, *Design Patterns*, 1994). The book's roles are Abstraction, RefinedAbstraction, Implementor and ConcreteImplementor.

Count the classes and the case makes itself. With inheritance only, you need shapes times renderers; with a bridge, shapes plus renderers. Three shapes and three renderers need 3 × 3 = 9 classes the first way and 3 + 3 = 6 with a bridge. Five shapes and four renderers need 5 × 4 = 20 against 5 + 4 = 9. Six of each need 6 × 6 = 36 against 6 + 6 = 12. Adding one renderer costs one class instead of one per shape.

The class diagram shows the two hierarchies and the single reference that joins them.

Interview questions

  • What is the structure of the Bridge pattern, and where exactly is the bridge?
  • How is Bridge different from Strategy?
  • How is Bridge different from Adapter?
  • Show the smell that Bridge removes, and the fix.
  • Who creates the implementor, and can it change at run time?

Sign up free to read the full topic

More Low-Level Design topics

Start free on Cariara · Coding problems · System design studio