以下内容摘抄于《C#大话设计模式》
桥接模式(Bridge),将抽象部分与它的实现部分分离,使它们都可以独立地变化。
桥接模式的结构图:
代码如下:
package com.schema.bridge;
public abstract class Implementor {
public abstract void OperationImp();
}
package com.schema.bridge;
public class ConcreteImplementorA extends Implementor {
public void OperationImp(){
System.out.println("Concrete implementor A method.");
}
}
package com.schema.bridge;
public class ConcreteImplementorB extends Implementor{
public void OperationImp(){
System.out.println("Concrete implementor B method.");
}
}
package com.schema.bridge;
public abstract class Abstraction {
protected Implementor implementor;
public void SetImplementor(Implementor implementor){
this.implementor = implementor;
}
public abstract void Operation();
}
package com.schema.bridge;
public class RefinedAbstraction extends Abstraction{
public void Operation(){
implementor.OperationImp();
}
}
客户端代码如下:
package com.schema.bridge;
public class AppMain {
public static void main(String[] args) {
Abstraction ab = new RefinedAbstraction();
ab.SetImplementor(new ConcreteImplementorA());
ab.Operation();
ab.SetImplementor(new ConcreteImplementorB());
ab.Operation();
}
}
运行结果如下: