Bridge Design Pattern

The Bridge Pattern does essentially the same thing as the Strategy Pattern but for implementations.

Although it’s optional, the Bridge pattern lets you replace the implementation object inside the abstraction. It’s as easy as assigning a new value to a field.

It allows you to separate the abstraction from the implementation:

Bridge is a structural design pattern that lets you split a large class or a set of closely related classes into two separate hierarchies—abstraction and implementation—which can be developed independently of each other.

Consider the following example: You have a Shape class that contains subclasses Circle and Square. We want to extend so they can have Red and Blue shape subclasses. However, it would not make sense to make two more classes named BlueCircle and RedSquare. Instead, we use Bridge pattern that attempts to solve the problem as follow:

Solve this problem by switching from inheritance to the object composition. What this means is that you extract one of the dimensions into a separate class hierarchy, so that the original classes will reference an object of the new hierarchy, instead of having all of its state and behaviours within one class.

Now think of Color as the implementations. Shape class gets a reference field pointing to one of the colour objects. The reference acts as a bridge between Shape and Colour classes. From now on, adding new colours won’t require changing the shape hierarchy, and vice versa.

Structure

  1. The Abstraction provides high-level control logic. It relies on the implementation object to do the actual low-level work.
  2. The Implementation declares the interface that’s common for all concrete implementations. An abstraction can only communicate with an implementation object via methods that are declared here.
  3. Concrete Implementations contain platform-specific code.
  4. Refined Abstractions provide variants of control logic. Like their parent, they work with different implementations via the general implementation interface.
  5. Usually, the Client is only interested in working with the abstraction. However, it’s the client’s job to link the abstraction object with one of the implementation objects.

UML for Bridge Pattern