Bridge Pattern


Problem


Applications that try to support many platforms often end up becoming brittle and bloated. Alternate implementations are locked in at compile time to their interfaces.

Solution


Create another layer of abstraction: decouple the abstraction from its implementation so the two can vary independently. Goes beyond encapsulation to insulation. This allows run-time flexibility compared to compile-time flexibility.

Related Patterns


  • Adapter (Adapter makes intends to make things work after they're designed, while Bridge intends to make them work before they're designed)
  • State
  • Strategy
  • Abstract Factory

Discussion


The Bridge pattern is applicable when you need run-time binding of client implementation and when you need to share an implementation among several objects. Applying the Bridge pattern results in a decoupled object interface while improving extensibility and hiding unnecessary details from clients.

Examples


The action of a switching something on and off can be represented with the Bridge pattern. When you need to switch something, the Bridge will decide at run-time what kind of switch we're interacting with and perform the correct operation, be it a normal lightswitch, a pull-chain, or some sort of knob.

Code


Bridge is a Bridge for Shapes and Windows.

class Shape{
  $x; $y;
}
class Window{
  $w; $h;
}

class Bridge{
  $shape = new Shape(400, 500);
  $window = new Window(800, 600);
}