什么是桥梁模式
桥梁模式一头连接抽象,一头连接实现。将原本在一起的逻辑通过抽象与实现解耦,使高层抽象的结构不随实际实现变化而变化。
为什么要用桥梁模式
应对实现多变的场景,桥梁模式能把外部逻辑抽象出去,从而将内部实现与外部抽象逻辑分离。
桥梁模式组成
外部抽象角色
public abstract class AbstractShell {
private Implementor implementor;
/**
* 子类需重新构造方法
* @param implementor implementor
*/
public AbstractShell(Implementor implementor) {
this.implementor = implementor;
}
public void innerFun() {
this.implementor.foo1();
}
public Implementor getImplementor() {
return implementor;
}
}
实现角色
public interface Implementor {
void foo1();
void foo2();
}
具体抽象角色
public class ComShell extends AbstractShell {
public ComShell(Implementor implementor) {
super(implementor);
}
@Override
public void innerFun() {
super.innerFun();
super.getImplementor().foo2();
}
}
具体实现角色
public class ComImplementor implements Implementor {
@Override
public void foo1() {
System.out.println("com foo1");
}
@Override
public void foo2() {
System.out.println("com foo2");
}
}
测试驱动
public class Client {
public static void main(String[] args) {
Implementor implementor = new ComImplementor();
AbstractShell shell = new ComShell(implementor);
shell.innerFun();
}
}