The bridge pattern is another structural design pattern meant to solve common issues with object structures. This pattern is used whenever we need to decouple the abstraction from the implementation of an object.
Problem Statement
Let’s say that you are working on software that represents animals. You have a Animal abstract class, and two implementations in the form of two concrete classes, lion and giraffe. We can imagine that you need to add a gender property to each animal, so you end up having a gender abstract class with two implementations for female and male. With this implementation, you will have 4 concrete classes in total: maleLion, femaleLion, maleGiraffe, femaleGiraffe, so the diagram of your program will look like this:
![](https://i0.wp.com/bitheap.techwp-content/uploads/2022/05/image-1.png?resize=957%2C505&ssl=1)
As you may have observed, this is not very efficient, but we can refactor this using the bridge pattern. Essentially, we can use composition instead of inheritance to solve this, by extracting the gender dimension as a separate class, and establish a has-a relationship between the Animal class and the gender class. Using this idea, our program will look something like this:
![](https://i0.wp.com/bitheap.techwp-content/uploads/2022/05/image.png?resize=973%2C498&ssl=1)
The important aspect of this pattern is that it can bridge two abstractions together, like animal and gender abstract classes in our case. This is achieved not through inheritance, but through composition, as the gender will be contained in each class implementing the Animal abstraction.
Where to Use It?
In my opinion, the best use case for this pattern is when you want to refactor big classes with several responsibilities. In a real-life situation, imagine the scenario of having a class responsible to connect and interact with several databases of different providers. You can separate the provider dimension in a separate class and “bridge” those two using this pattern.
Pitfalls
A disadvantage related to this class is that you can increase the complexity of your program by using it, instead of simplify it. Some monolithic classes may be cohesive despite of their sizes, and decoupling dimensions from them may increase the overall complexity of the code.
Another pitfall is that you may end up with many interfaces having a single implementation. This however, can also be a good example of enforcing the single responsibility principle, but generally this will lead to a more complex program with many different relationships between classes.
If you are interested to learn more about adapter pattern, and about design patterns in general, I have published this course on Udemy. You can see there all the known design patterns described in detail with relevant, real-world examples.
What do you think about the bridge pattern? Looking forward to reading your opinion in the comment section.