Bridge

Java Fundamentals and Patterns

javase
bridge
design-patterns
concepts
What is the Bridge Structural Design-Pattern
Author

Carla Velasco

Published

Tuesday, June 1, 2021

Modified

Friday, November 1, 2024

1 Definition

The bridge pattern is a design pattern in computer programming and Java that is used to decoumple abstraction from implemetation, allowing them to change independently..


The Bridge pattern is a way to separate the idea of what something does from how it does it, so that both can evolve independently.

Imagine you want to draw different shapes, like circles, but in different colors. You could create a class for each shape and color combination, but that would be a lot of classes. Instead, the Bridge pattern separates the “what” (the shape) from the “how” (the color) and combines them when needed. This way, you can have different classes for the shapes and different classes for the colors, and they can be combined in different ways without having to change either.

2 Example: Building a DrawAPI

Here’s an example of the explanation above:

  1. Create an interface DrawAPI with a method to draw a circle.
interface DrawAPI {
   void drawCircle(int radius, int x, int y);
}
  1. Implement the DrawAPI interface.
class RedCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: red, radius: " + radius + ", x: " + x + ", " + y + "]");
   }
}

class GreenCircle implements DrawAPI {
   @Override
   public void drawCircle(int radius, int x, int y) {
      System.out.println("Drawing Circle[ color: green, radius: " + radius + ", x: " + x + ", " + y + "]");
   }
}
  1. Create an abstract class Shape with a field of type DrawAPI:
abstract class Shape {
   protected DrawAPI drawAPI;
   
   protected Shape(DrawAPI drawAPI){
      this.drawAPI = drawAPI;
   }
   public abstract void draw();
}
  1. Create concrete classes that extend the Shape class and use the drawAPI to draw a circle.
class Circle extends Shape {
   private int x, y, radius;

   public Circle(int x, int y, int radius, DrawAPI drawAPI) {
      super(drawAPI);
      this.x = x;  
      this.y = y;  
      this.radius = radius;
   }

   public void draw() {
      drawAPI.drawCircle(radius,x,y);
   }
}
  1. Use the Shape and DrawAPI classes to draw different colored circles.
public class BridgePattern {
   public static void main(String[] args) {
      Shape redCircle = new Circle(100,100, 10, new RedCircle());
      Shape greenCircle = new Circle(100,100, 10, new GreenCircle());

      redCircle.draw();
      greenCircle.draw();
   }
}

Output:

Drawing Circle[ color: red, radius: 10, x: 100, 100]
Drawing Circle[ color: green, radius: 10, x: 100, 100]

About this site

Back to top