简介:把事物对象和其具体行为、具体特征分离开来,使它们可以各自独立的变化,事物对象仅是一个抽象的概念;
如“圆形”、“三角形”归于抽象的“形状”之下,而“画圆”、“画三角”归于实现行为的“画图”类之下,然后由“形状”调用“画图”。
目的:
总结:将抽象和行为实现分离,实现类的最小设计原则,保持独立性
组成:抽象类, 行为接口,行为实现
1,抽象类
package com.design.n.bridge;/** * 抽象类 */public abstract class Car { //定义引擎 private EngineService engineService; public Car(EngineService engineService) { super(); this.engineService = engineService; } //定义子类的实现细节 public abstract void installEngine(); public EngineService getEngineService() { return engineService; }}
package com.design.n.bridge;/** * Bus汽车实现细节 */public class BusCar extends Car{ public BusCar(EngineService engineService) { super(engineService); } @Override public void installEngine() { System.out.print("Bus 汽车 : 安装引擎 ... ... "); this.getEngineService().installEngine(); }}
package com.design.n.bridge;/** * Jeep汽车实现细节 */public class JeepCar extends Car{ public JeepCar(EngineService engineService) { super(engineService); } @Override public void installEngine() { System.out.print("Jeep 汽车 : 安装引擎 ... ... "); this.getEngineService().installEngine(); }}
2,行为接口
package com.design.n.bridge;/** * 引擎接口 * * 桥接模式 - 行为实现 */public interface EngineService { /** * 安装引擎 */ void installEngine();}
3,行为实现类
package com.design.n.bridge;/** * 引擎-A */public class AEngineServiceImpl implements EngineService { @Override public void installEngine() { System.out.println("安装引擎 - A"); }}
package com.design.n.bridge;/** * 引擎 - B */public class BEngineServiceImpl implements EngineService { @Override public void installEngine() { System.out.println("安装引擎 - B"); }}
4,Main
package com.design.n.bridge;/** * 桥接模式 * * 概括:将抽象和行为实现分离,实现类的最小设计原则,保持独立性 */public class MainTest { public static void main(String[] args) { //行为实现 EngineService engineA = new AEngineServiceImpl(); EngineService engineB = new BEngineServiceImpl(); //抽象类 Car bus = new BusCar(engineA); bus.installEngine(); Car jeep = new JeepCar(engineB); jeep.installEngine(); }}
6,Result
Bus 汽车 : 安装引擎 ... ... 安装引擎 - AJeep 汽车 : 安装引擎 ... ... 安装引擎 - B