Bridge Design Pattern
Bridge pattern is one of the Structural Design Patterns. Consider the problem given in the image below where there is one parent class car and from it we are extending different types of cars - Pink Sedan Blue Wheels, Pink Sedan Red Wheels, ... , Red Sedan Blue Wheels, ... Pink Hatchback blue wheels etc.
We can observe that the base class is being extended in different dimensions - Different types of wheels, different types of car types and different types of car colors. As there is only a single base class for car, the number of extended classes is very large. And thus even a simple operation like launching a new type of sound system means a lot of developer efforts because a lot of classes need to be created (every car type for every wheel type for every required color for each sound system type). Observe how the number of classes required increase exponentially. And it only gets worse.
Solution? Here comes the bridge pattern. When you have a class that can be extended in multiple dimensions you can decompose the different dimensions to composition.
Step #1 - Creating composition classes (Implementation)
Create a parent class Color and extend different colors from it. Similarly create a class Wheel and extend different types of wheels from it.
Step #2 - Creating the parent object (Abstraction) and composing other dimensions in it
Now put a Wheel object and a Color object (Composition) inside the Car class. And extend the car types like Sedan, Hatchback from the Car object (Extension).
Step #3 - Creating the different types of objects
Finally, let's create the objects of different required configurations.
Advantages
The Bridge pattern separates the abstraction (e.g., interface or abstract class) from its implementation, allowing them to vary independently. This promotes flexibility and simplifies changes to either side without affecting the other. This imporves Maintainability, Extensibility and Reusability.
Disadvantages
Complexity Overhead: Implementing the Bridge pattern introduces additional complexity compared to simpler design patterns. It requires defining separate abstraction and implementation hierarchies, which can be overkill for smaller projects or simple variations.
Potential Performance Impact: Depending on the design and usage, the Bridge pattern may introduce a slight performance overhead due to the use of abstraction-indirection. However, modern compilers and optimizations often mitigate this impact to a negligible level in most cases.
References
To write this article I took help from the following sources:
https://refactoring.guru/design-patterns/bridge
https://medium.com/@amritlalsahu5/bridge-design-pattern-9afad7138777
Hope you liked this short article post. I post such content regularly. Follow Prateek Mishra to learn something new every week.