Bridge Pattern

Real-World Example

Code 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.

    The abstraction may list the same methods as the implementation, but usually, the abstraction declares some complex behaviors that rely on a wide variety of primitive operations declared by the implementation.

  3. Concrete Implementations contain platform-specific code.

  4. Refined Abstractions provide variants of control logic. As 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.

  • Abstraction: defines the abstraction’s interface
  • RefinedAbstraction: extends the interface defined by Abstraction
  • Implementor: defines the interface for implementation classes
  • ConcreteImplementor: implements the Implementor interface and defines its concrete implementation.

Code Examples

Applicability

Use the Bridge pattern when

  • You want to avoid a permanent binding between an abstraction and its implementation. This might be the case, for example, when the implementation must be selected or switched at run-time.
  • Both the abstractions and their implementations should be extensible by subclassing. In this case, the Bridge pattern lets you combine the different abstractions and implementations and extend them independently.
  • Changes in the implementation of an abstraction should have no impact on clients; that is, their code should not have to be recompiled.
  • You have a proliferation of classes. Such a class hierarchy indicates the need for splitting an object into two parts. Rumbaugh uses the term “nested generalizations” to refer to such class hierarchies.
  • You want to share an implementation among multiple objects (perhaps using reference counting), and this fact should be hidden from the client. A simple example is Coplien’s String class, in which multiple objects can share the same string representation

Comparisons

Resources