Sablonul de proiectare Bridge

Descriere

Bridge este un sablon structural. Cu ajutorul acestui sablon se poate decupla abstractizarea de implementare in asa fel incat acestea sa poata varia in mod independent. Dezavantajul acestui sablon este acela al cresterii gradului de complexitate al aplicatiei.

Diagrama UML

Exemplu

Interfata Bridge:

public interface DrawAPI {
   public void drawCircle(int radius, int x, int y);
}

Implementarea interfetei Bridge:

public 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 + "]");
   }
}
 
public 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 + "]");
   }
}

Clasa abstracta ce utilizeaza interfata Bridge:

public abstract class Shape {
   protected DrawAPI drawAPI;
 
   protected Shape(DrawAPI drawAPI){
      this.drawAPI = drawAPI;
   }
   public abstract void draw();	
}

Implementarea clasei:

public 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);
   }
}

Testare:

public class BridgePatternDemo {
   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();
   }
}

Rezultatul rularii codului:

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

Refernte