Java Top

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 on Wednesday:

>> CHECK OUT THE COURSE

1. Overview

The official definition for the Bridge design pattern introduced by Gang of Four (GoF) is to decouple an abstraction from its implementation so that the two can vary independently.

This means to create a bridge interface that uses OOP principles to separate out responsibilities into different abstract classes.

2. Bridge Pattern Example

For the Bridge pattern, we'll consider two layers of abstraction; one is the geometric shape (like triangle and square) which is filled with different colors (our second abstraction layer):

First, we'll define a color interface:

public interface Color {
    String fill();
}

Now we'll create a concrete class for this interface:

public class Blue implements Color {
    @Override
    public String fill() {
        return "Color is Blue";
    }
}

Let's now create an abstract Shape class which consists a reference (bridge) to the Color object:

public abstract class Shape {
    protected Color color;
    
    //standard constructors
    
    abstract public String draw();
}

We'll now create a concrete class of Shape interface which will utilize method from Color interface as well:

public class Square extends Shape {

    public Square(Color color) {
        super(color);
    }

    @Override
    public String draw() {
        return "Square drawn. " + color.fill();
    }
}

For this pattern, the following assertion will be true:

@Test
public void whenBridgePatternInvoked_thenConfigSuccess() {
    //a square with red color
    Shape square = new Square(new Red());
 
    assertEquals(square.draw(), "Square drawn. Color is Red");
}

Here, we're using the Bridge pattern and passing the desired color object. As we can note in the output, the shape gets draws with the desired color:

Square drawn. Color: Red
Triangle drawn. Color: Blue

3. Conclusion

In this article, we had a look at the bridge design pattern. This is a good choice in the following cases:

  • When we want a parent abstract class to define the set of basic rules, and the concrete classes to add additional rules
  • When we have an abstract class that has a reference to the objects, and it has abstract methods that will be defined in each of the concrete classes

The full source code for this example is available over on GitHub.

Java bottom

The early-bird price of the new Learn Spring Security OAuth course packages will increase by $50 on Wednesday:

>> CHECK OUT THE COURSE

Leave a Reply

avatar
  Subscribe  
Notify of