# Bridge

In 
Published 2022-12-03

This tutorial explains to you the design pattern named Bridge (which is a Structural Pattern).

# Bridge Pattern - theory

A Bridge is used when we need to decouple/separate the abstraction from its implementation so that the two can vary independently. The Bridge Pattern is also known as Handle or Body.

The bridge is used when we have a hierarchy like this:

... but we prefer to have something like this:

The last design is using the Bridge Design Pattern.

As you can see, when we use the Bridge Design Pattern, we :

  • have fewer classes to create and maintain
  • if we want to change something to a Color class we will modify into one place and the modification will be "seen/ propagated" into a Shape class
  • prefer composition to inheritance

Here it is the UML Diagram for Bridge Pattern (for my example):

# Bridge Pattern - example

Here is an example for showing how the Bridge Pattern works in Java :

package bridge_example_java;
 
  public interface Color {
    public String setColor();
     
}
package bridge_example_java;
 
public abstract class Shape {
     
    // A Shape contains a Color object (composition) !!!
    protected Color color;
      
    //When you create a Shape you provide Color object to it
    public Shape(Color c){
        this.color=c;
    }
      
    abstract public void drawAndColor();
}
package bridge_example_java;
 
public class Rectangle extends Shape{
      
    public Rectangle(Color c) {
        super(c);
    }
  
    @Override
    public void drawAndColor() {
         System.out.println("The RECTANGLE was filled with "+color.setColor()+" color. ");
    } 
  
}
package bridge_example_java;
 
public class Circle extends Shape{
      
    public Circle(Color c) {
        super(c);
    }
  
    @Override
    public void drawAndColor() {
        System.out.println("The CIRCLE was filled with "+color.setColor()+" color. ");
    } 
  
}
package bridge_example_java;
 
public class RedColor implements Color{
      
    public String setColor(){
        return "RED";
    }
 
}
package bridge_example_java;
 
public class GreenColor  implements Color{
      
    public String setColor(){
        return "GREEN";
    }
 
}
package bridge_example_java;
 
public class BridgePatternExample {
     
    public static void main(String[] args) {
         
        Shape rectangle = new Rectangle(new RedColor());
        rectangle.drawAndColor();
          
        Shape circle = new Circle(new GreenColor());
        circle.drawAndColor();
         
    }
     
}

And here you have the example result :