Real World Example
Consider you have a website with different pages and you are supposed to allow the user to change the theme. What would you do? Create multiple copies of each of the pages for each of the themes or would you just create separate theme and load them based on the user’s preferences? Bridge pattern allows you to do the second.
In Plain Words
Bridge pattern is about preferring composition over inheritance. Implementation details are pushed from a hierarchy to another object with a separate hierarchy.Wikipedia Definition
The bridge pattern is a design pattern used in software engineering that is meant to “decouple an abstraction from its implementation so that the two can vary independently”
Programmatic Example
Translating our WebPage example from above. Here we have theWebPage hierarchy:
Key Participants
Abstraction
Abstraction
Defines the abstract interface and maintains a reference to the Implementor (in our example:
WebPage interface)Refined Abstraction
Refined Abstraction
Extends the interface defined by Abstraction (in our example:
About, Careers)Implementor
Implementor
Defines the interface for implementation classes (in our example:
Theme interface)Concrete Implementor
Concrete Implementor
Implements the Implementor interface (in our example:
DarkTheme, LightTheme, AquaTheme)When to Use?
Use the Bridge pattern when:
- You want to avoid a permanent binding between an abstraction and its implementation
- Both the abstractions and their implementations should be extensible by subclassing
- Changes in the implementation of an abstraction should have no impact on clients
- You want to hide the implementation of an abstraction completely from clients
- You have a proliferation of classes resulting from a coupled interface and numerous implementations
Benefits
- Decoupling: Separates abstraction from implementation so they can vary independently
- Improved Extensibility: You can extend abstraction and implementation hierarchies independently
- Hiding Implementation Details: You can shield clients from implementation details
- Single Responsibility: Abstraction focuses on high-level logic, implementation on platform details
Comparison: Inheritance vs Bridge
With Bridge pattern, you have:
- 2 page types (About, Careers)
- 3 themes (Dark, Light, Aqua)
- Total: 5 classes instead of 6, and it scales much better!
Related Patterns
- Abstract Factory: Can be used to create and configure a particular Bridge
- Adapter: Makes unrelated classes work together, while Bridge is designed up-front to let abstraction and implementation vary independently