DEV Community

Shirin Monzavi
Shirin Monzavi

Posted on

What is Bridge Design Pattern?

๐Ÿš€All things you should know about bridge design pattern

โ‰๏ธ Motivation
Decouple an abstraction from its implementation so that both can evolve independently. It belongs to the structural category.

๐ŸŒ Real-World Scenario
When an abstraction can have multiple implementations, the typical approach is inheritance. But this leads to some issues.
Letโ€™s say we have an abstract class Window, with two implementations: XWindow and PMWindow. If we use inheritance and want to add a new type like IconWindow, weโ€™ll need to create XIconWindow and PMIconWindow.
This leads to:

1๏ธโƒฃ Class explosion โ€“ For every new window type, we must implement it for each platform.

2๏ธโƒฃ Tight coupling โ€“ The client is forced to choose a concrete platform (XWindow or PMWindow), tying the code to a specific implementation.

Image description

๐ŸŽฏ Solution โ€” Bridge Pattern
The Bridge pattern solves this by splitting the abstraction (Window, IconWindow, TransientWindow, etc.) from the implementation (WindowImp, XWindowImp, PMWindowImp, etc.).
๐Ÿ’ก The abstraction holds a reference to the implementation, and they communicate through a defined interface. This bridges the two hierarchies, enabling independent evolution and better flexibility.

Image description

๐Ÿ’Ž Related Patterns
โ€ข Abstract Factory can help create and configure a particular Bridge.
โ€ข Adapter lets unrelated classes work together, but it's applied after design.
โ€ข Bridge is a design-time decision to decouple abstraction from implementation.

๐Ÿ“‚** Code Example**
See it in action:
๐Ÿ‘‰ GitHub - https://github.com/shirin-monzavi/BridgeDesignPatternSample

๐Ÿ’ฌ Your Turn!
โ“Have you ever used the Bridge Pattern in your projects?

Image description

Top comments (0)