设计模式之桥接 Bridge

2018-11-22  本文已影响0人  音符纸飞机

重点

public interface DrawAPI {
   public void draw();
}

public class RedPencil implements DrawAPI {
   @Override
   public void draw() {
      System.out.println("Drawing with Red Pencil");
   }
}

public class GreenPen implements DrawAPI {
   @Override
   public void draw() {
      System.out.println("Drawing with Green Pen");
   }
}

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

public class Circle extends Shape {
 
   public Circle(DrawAPI drawAPI) {
      super(drawAPI);
   }
 
   public void draw() {
      drawAPI.draw();
   }
}

public class Rectangle extends Shape {
 
   public Rectangle(DrawAPI drawAPI) {
      super(drawAPI);
   }
 
   public void draw() {
      drawAPI.draw();
   }
}

public class BridgePatternDemo {
   public static void main(String[] args) {
      Shape redCircle = new Circle(new RedPencil());
      Shape greenRectangle = new Rectangle(new GreenPen());
 
      RedPencil.draw();
      GreenPen.draw();
   }
}

上一篇 下一篇

猜你喜欢

热点阅读