桥接模式
将抽象与实现分离,使它们可以独立变化。它是用组合关系代替继承关系来实现,从而降低了抽象和实现这两个可变维度的耦合度。
组成
1 2 3 4
| - '实现化'(Implementor)角色:定义实现化角色的接口,供扩展抽象化角色调用。 - '具体实现化'(Concrete Implementor)角色:给出实现化角色接口的具体实现。 - '抽象化'(Abstraction)角色:定义抽象类,并包含一个对实现化对象的引用。 - '扩展抽象化'(Refined Abstraction)角色:是抽象化角色的子类,实现父类中的业务方法,并通过组合关系调用实现化角色中的业务方法。
|
优点
(1) 由于抽象与实现分离,所以扩展能力强;
(2) 可动态的切换实现
由于桥接模式实现了抽象和实现的分离,所以在实现桥接模式时,就可以实现动态的选择和使用具体的实现。
(3) 实现细节对客户端透明,可以对用户隐藏实现细节。
缺点
(1) 由于聚合关系建立在抽象层,要求开发者针对抽象化进行设计与编程,这增加了系统的理解与设计难度。
(2) 桥接模式要求正确识别出系统中两个独立变化的维度,因此其使用范围有一定的局限性。
应用场景
(1)当一个类存在两个独立变化的维度,且这两个维度都需要进行扩展时。
(2)当一个系统不希望使用继承或因为多层次继承导致系统类的个数急剧增加时。
(3)当一个系统需要在构件的抽象化角色和具体化角色之间增加更多的灵活性时。
实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| public class BridgeTest { public static void main(String[] args) { Implementor imple=new ConcreteImplementorA(); Abstraction abs=new RefinedAbstraction(imple); abs.Operation(); } }
interface Implementor { public void OperationImpl(); }
class ConcreteImplementorA implements Implementor { public void OperationImpl() { System.out.println("具体实现化(Concrete Implementor)角色被访问" ); } }
abstract class Abstraction { protected Implementor imple; protected Abstraction(Implementor imple) { this.imple=imple; } public abstract void Operation(); }
class RefinedAbstraction extends Abstraction { protected RefinedAbstraction(Implementor imple) { super(imple); } public void Operation() { System.out.println("扩展抽象化(Refined Abstraction)角色被访问" ); imple.OperationImpl(); } }
|