🏠Spring BootBridge Design Pattern

Bridge Design Pattern

Java Spring Boot

The Bridge design pattern is a structural pattern that deals with decoupling abstraction and its implementation. It lets you split a set of related classes into two separate abstraction and implementation hierarchies. As these are now separated, you can develop them independently of each other. Let’s understand this design pattern with an example in Java.

Understanding the Problem

Let’s say you have a bunch of Shape classes called Circle and Square. Now you need to add colors to these shapes. Let’s say the identified colours are Red and Green. This means that you would end up with four classes like GreenSquare and RedCircle. For example, our java classes without bridge design pattern look like below.

With this approach, your number of classes will increase over time. For example, including one more color would add two more shape classes. This is ideally not sustainable and is technical debt. Also, this makes refactoring a lot harder in the future.

Introducing Bridge Pattern

If you notice the above example, both GreenSquare and RedSquare has the same logic except for the colors. If we could extract this implementation outside of the shapes, then we can reduce the number of classes.

As you see here, The colors(Implementation) were separated from the shapes. Shapes will now look for a Color interface(Abstraction). This is a fine example of bridge design pattern in Java.

With this approach, you can keep adding colors and shapes without having to worry about the number of classes.

You can find the code for all these examples at our Design pattern GitHub repository.

Advantages and disadvantages of Bridge Pattern

Less refactoring in the future as the number of classes won’t increase as much.If you are not adding further features, then the bridge pattern would add more classes.
Both sides of abstraction and implementation can be developed independently
Single Responsibility Principle: Updating one component won’t affect others.
Multiple people can work simultaneously on different components with this approach

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *