Codacoda
Back to Academy

design patterns

Bridge

The Bridge pattern decouples an abstraction from its implementation so that the two can vary independently. Instead of a monolithic class hierarchy, you split it into two separate hierarchies — abstraction and implementation — and connect them with a bridge (composition). The key participants are the Abstraction (defines the abstraction's interface and holds a reference to the Implementor), RefinedAbstraction (extends the Abstraction), Implementor (defines the interface for implementation classes), and ConcreteImplementor (implements the Implementor interface). Think of a remote control (abstraction) and a TV (implementation): any remote can work with any TV brand because they communicate through a standard interface. Use Bridge when you want to avoid a permanent binding between an abstraction and its implementation, or when both the abstraction and implementation should be extensible by subclassing.

Use Cases

  • Rendering engines that work across multiple platforms
  • Notification system with multiple channels (email, SMS, push)
  • Database drivers supporting different databases via same API
  • Device drivers abstracting hardware from software layers

Visualization

implAbstraction+operation()#implRefinedAbstraction+operation()<<interface>>Implementor+operationImpl()ConcreteImplA+operationImpl()ConcreteImplB+operationImpl()
Speed:1x
Bridge — decouples an abstraction from its implementation so they vary independentlyStep 1 / 7

Implementation

Output

Click "Run Code" to see output...