java23种设计模式(四)-- 桥接模式
参考地址:http://www.jasongj.com/design_pattern/bridge/
实现系统可从多种维度分类,桥接模式将各维度抽象出来,各维度独立变化,之后可通过聚合,将各维度组合起来,减少了各维度间的耦合。
代码示例:
1、创建一个车的抽象类(车可以按照牌子分类--BMW,BenZ,Land Rover等,也可以按照变数器分类--手动档、自动档、手自一体)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * author:YZH 3 * time: 2019/6/11 14:27 4 * description: 创建抽象类车,并将车的变速器设置为车的一个属性 5 **/ 6 public abstract class Car { 7 protected Transmission transmission; 8 9 protected abstract void run(); 10 11 12 public void setTransmission(Transmission transmission){ 13 this.transmission = transmission; 14 } 15 }
2、创建变速器接口
/** * author:YZH * time: 2019/6/11 14:28 * description: 创建抽象类的车的变速器 **/ public interface Transmission { void gear(); }
3、创建BMW牌的车(继承Car)
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * author:YZH 3 * time: 2019/6/11 14:39 4 * description: BMWCar 5 **/ 6 public class BMWCar extends Car{ 7 @Override 8 protected void run() { 9 transmission.gear(); 10 System.out.println("BMW is running"); 11 } 12 }
4、创建手动挡(实现Transmission )
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * author:YZH 3 * time: 2019/6/11 14:41 4 * description: 手动挡 5 **/ 6 public class ManualTransmission implements Transmission { 7 @Override 8 public void gear() { 9 System.out.println("Manual transmission"); 10 } 11 }
5、代码调用
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /** 2 * author:YZH 3 * time: 2019/6/11 14:42 4 * description: 测试代码 5 **/ 6 public class BridgeClient { 7 public static void main(String[] args) { 8 Transmission transmission = new ManualTransmission(); 9 Car bwmCar = new BMWCar(); 10 bwmCar.setTransmission(transmission); 11 12 bwmCar.run(); 13 } 14 }
6、输出结果
Manual transmission
BMW is running
提示:如果还要创建不同品牌的车,并指定不同的变速器,只需要继承Car,新增变速器类型(实现Transmission )即可。