Tutorials Design Patterns Mastery
Bridge Pattern: Decoupling abstraction from implementation
On this page
The Bridge Pattern
The Bridge Pattern is designed to "decouple an abstraction from its implementation so that the two can vary independently." This is the ultimate fix for an inheritance hierarchy that is exploding out of control.
1. Solving "Class Explosion"
Imagine you have RemoteControl and Television. If you inherit (SonyRemote, SamsungRemote, SonySmartRemote...), your classes will multiply exponentially (N x M). The Bridge pattern says: "Stop inheriting. Connect them via a bridge."
public abstract class RemoteControl
{
protected IDevice _device; // THE BRIDGE
public abstract void TogglePower();
}
public interface IDevice
{
void On();
void Off();
}
2. Why use it?
Because of the bridge, you can create a new AppleRemote without ever touching the Television code, and you can create a new SmartProjector without ever touching the RemoteControl code. They are completely independent.
4. Interview Mastery
Q: "How is the Bridge pattern different from the Strategy pattern?"
Architect Answer: "Structural vs Behavioral. The **Bridge** is a Structural pattern used during the *Design Phase* to organize your class hierarchies so they don't grow out of control. The **Strategy** is a Behavioral pattern used during the *Runtime Phase* to switch an algorithm inside a class. Bridge is 'What the system is built of', Strategy is 'How a task is performed'."