NBA之桥梁模式

135 阅读1分钟

Design Pattern:

Bridge is used when we need to decouple an abstraction from its implementation so that the two can vary independently 模式:桥梁模式就是用来解耦的,遵循面向对象的开放-闭合原则

编个故事:我们篮球队要选一个人(People)去参加篮球选拔,大家都说选天翔吧(TissanLuo), 但是我篮球打得真的很烂,教练拿出了看家宝贝,curry和durant的球衣,只要穿上它就可以 投出库里的三分,使出杜兰特的暴扣,果然很牛逼,不信你看运行结果。

球衣的接口
  public interface Clothes {
  
      public void show();
  
  }
  //库里的球衣 
  public class CurryClothes implements Clothes {
      @Override
      public void show() {
          System.out.println("curry的投三分球");
      }
  }
  //杜兰特的球衣
  public class DurantClothes implements Clothes {
      @Override
      public void show() {
        System.out.println("durant的超远暴扣");
      }
  }

穿球衣的球员抽象

public abstract class People {

    private Clothes clothes;

    public People(Clothes clothes) {
        this.clothes = clothes;
    }

    public void show(){
        clothes.show();
    }
}
    
//实不相瞒 TissanLuo 就是我  我准备穿别人的球衣了
public class TissanLuo extends People {

    public TissanLuo(Clothes clothes) {
        super(clothes);
    }

}

比赛开始了

public class BridgeDemo {

    public static void main(String[] args) {
            People tissanLuo = new TissanLuo(new CurryClothes());
            tissanLuo.show();
    
            tissanLuo = new TissanLuo(new DurantClothes());
            tissanLuo.show();
        }
}

结果