一、什么是桥接模式
Bridge 模式又叫做桥接模式,是构造型的设计模式之一。Bridge模式基于类的最小设计原则,通过使用封装,聚合以及继承等行为来让不同的类承担不同的责任。它的主要特点是把抽象(abstraction)与行为实现(implementation)分离开来,从而可以保持各部分的独立性以及应对它们的功能扩展。
二、桥接模式的结构
三、桥接模式的角色和职责
Client
Bridge模式的使用者
Abstraction
抽象类接口(接口或抽象类)
维护对行为实现(Implementor)的引用
Refined Abstraction
Abstraction子类
Implementor
行为实现类接口 (Abstraction接口定义了基于Implementor接口的更高层次的操作)
ConcreteImplementor
Implementor子类
代码实现:
Implementor类:
package com.qianyan.bridge; public interface Engine { /** * 安装发动引擎 */ public void installEngine(); }
package com.qianyan.bridge; public class Engine2000 implements Engine { @Override public void installEngine() { System.out.println("安装2000CC发动引擎"); } }
package com.qianyan.bridge; public class Engine2200 implements Engine { @Override public void installEngine() { System.out.println("安装2200CC发动引擎"); } }
package com.qianyan.bridge; public abstract class Car { private Engine engine; public Car(Engine engine) { this.engine = engine; } public Engine getEngine() { return engine; } public void setEngine(Engine engine) { this.engine = engine; } public abstract void installEngine(); }
Refined Abstraction类:
package com.qianyan.bridge; public class Bus extends Car { public Bus(Engine engine) { super(engine); } @Override public void installEngine() { System.out.print("Bus:"); this.getEngine().installEngine(); } }
package com.qianyan.bridge; public class Jeep extends Car { public Jeep(Engine engine) { super(engine); } @Override public void installEngine() { System.out.print("Jeep:"); this.getEngine().installEngine(); } }
package com.qianyan.bridge; public class MainClass { public static void main(String[] args) { Engine engine2000 = new Engine2000(); Engine engine2200 = new Engine2200(); Car bus = new Bus(engine2000); bus.installEngine(); Car jeep = new Jeep(engine2200); jeep.installEngine(); } }
Bus:安装2000CC发动引擎 Jeep:安装2200CC发动引擎