美文网首页
设计模式之桥接 Bridge

设计模式之桥接 Bridge

作者: 音符纸飞机 | 来源:发表于2018-11-22 18:22 被阅读0次

    重点

    • 抽象与实现分离
    • 解决继承爆炸、用于系统有多个角度分类。(下面的例子,可已根据shape分类,也可以根据draw的颜色分类)不使用桥接模式的情况下,如果有三个角度分类、每个角度有两个分类的话,需要继承实现2^3=8个类,用了桥接模式只需要继承实现2*3=6个类。


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

    相关文章

      网友评论

          本文标题:设计模式之桥接 Bridge

          本文链接:https://www.haomeiwen.com/subject/pmclqqtx.html