1.定义
Bridge模式又叫做桥接模式,是构造型的设计模式之一。Bridge模式基于类的最小的设计原则,通过使用封装,聚合以及继承等行为来让不同的类承担不同的责任。它的主要特点是把抽象(abstraction)与行为实现(implementation)分离开来,从而可以保持各部分的独立性以及应对他们的功能扩展。
2.桥接模式的结构
3.桥接模式的角色和职责
- Client--Bridge模式的使用者
- Abstraction--抽象类接口(接口或抽象类),维护对行为实现(Implementor)
- Refined Abstraction--Abstraction子类
- Implementor--行为实现类接口(Abstraction接口定义了基于Implementor接口的更高层次的操作)
- ConcreteImplementor--Implementor子类
4.代码演示
package dwz.zheaven.bridge; /* * Implementor--行为实现类接口 */ public interface Engine { public void installEngine(); }
package dwz.zheaven.bridge; /* * ConcreteImplementor--Implementor子类 */ public class Engine2000 implements Engine { @Override public void installEngine() { System.out.println("安装2000cc发动机"); } }
package dwz.zheaven.bridge; /* * ConcreteImplementor--Implementor子类 */ public class Engine2200 implements Engine { @Override public void installEngine() { System.out.println("安装2200cc发动机"); } }
package dwz.zheaven.bridge; /* * ConcreteImplementor--Implementor子类 */ public class Engine2400 implements Engine { @Override public void installEngine() { System.out.println("安装2400cc发动机"); } }
package dwz.zheaven.bridge; /* * Abstraction--抽象类接口(接口或抽象类), * 维护对行为实现(引用Implementor) */ 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(); }
package dwz.zheaven.bridge; /* * Refined Abstraction--Abstraction子类 */ public class Bus extends Car { public Bus(Engine engine) { super(engine); } @Override public void installEngine() { System.out.print("bus:"); this.getEngine().installEngine(); } }
package dwz.zheaven.bridge; /* * Refined Abstraction--Abstraction子类 */ public class Jeep extends Car { public Jeep(Engine engine) { super(engine); } @Override public void installEngine() { System.out.print("jeep:"); this.getEngine().installEngine(); } }
package dwz.zheaven.bridge; /* * 测试代码 */ public class Main { public static void main(String[] args) { Engine engine = new Engine2000(); Engine engine2 = new Engine2200(); Car car = new Bus(engine); car.installEngine();//bus:安装2000cc发动机 Car car2 = new Bus(engine2); car2.installEngine();//bus:安装2200cc发动机 Car car3 = new Jeep(engine); car3.installEngine();//jeep:安装2000cc发动机 Car car4 = new Jeep(engine2); car4.installEngine();//jeep:安装2200cc发动机 } }