2019-03-03桥接模式

2019-03-03  本文已影响0人  Aluha_f289

桥接模式

桥接(Bridge)是用于把抽象化与实现化解耦,使得二者可以独立变化。

意图:将抽象部分与实现部分分离,使它们都可以独立的变化。

主要解决:在有多种可能会变化的情况下,用继承会造成类爆炸问题,扩展起来不灵活。

使用场景:一个类存在两个独立变化的维度,且这两个维度都需要进行扩展。

注意点:
    1、定义一个桥接口,使其与一方绑定,这一方的扩展全部使用实现桥接口的方式。
    2、定义一个抽象类,来表示另一方,在这个抽象类内部要引入桥接口,而这一方的扩展全部使用继承该抽象类的方式。

实现

步骤一、创建桥接实现接口。

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

步骤二、创建实现了 DrawAPI 接口的实体桥接实现类。

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

步骤三、使用 DrawAPI 接口创建抽象类 Shape。

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

步骤四、创建实现了 Shape 接口的实体类。

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

步骤五、使用 Shape 和 DrawAPI 类画出不同颜色的圆。

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

步骤六、执行程序,输出结果:

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

参考博客地址http://www.runoob.com/design-pattern/bridge-pattern.html

上一篇 下一篇

猜你喜欢

热点阅读