桥梁模式“将抽象化与实现化断耦,使得二者可以分别独立地变化”。
桥梁模式本身并不是很容易理解,但如果把它和移植J2ME的MIDP时所遇到的Peer相联系起来,就觉得很有价值了。
MIDP的标准类库是为用户提供的接口,在任何平台上都要保持一致,是不能变的,因而应该设计为抽象的,对平台无依赖性。以可视的控件为例,很多控件类都会有一个对应的Peer类,比如Form有FormPeer,Peer才是真正“做实事”的类,因而它也是依赖于平台的,在不同的平台上Peer的实现要不同。在Form中会有一个FormPeer的引用,在实现某一功能时,都是调用Peer去处理。Form对FormPeer的引用就成为一座桥梁,把抽象的部分与实做的部分联系起来,但它们之间又没有什么依赖关系,它们可以独立地改进。
以下是示例,其中RefinedAbstraction相当于上面说的Form,Abstraction相当于Component,Implementor相当于Peer,ConcreteImplementor相当于FormPeer。
package
bridge;
public abstract class Abstraction ... {
protected Implementor impl;
public void func() ...{
impl.impFunc();
}
}
package bridge;
public class RefinedAbstraction extends Abstraction ... {
public RefinedAbstraction () ...{
this.impl = new ConcreteImplementor();
}
public void func() ...{
super.func();
}
}
package bridge;
public abstract class Implementor ... {
public abstract void impFunc();
}
package bridge;
public class ConcreteImplementor extends Implementor ... {
public void impFunc() ...{
System.out.println(this + ".impFunc()");
}
}
package bridge;
public class Client ... {
public static void main(String[] args) ...{
(new RefinedAbstraction()).func();
}
}
public abstract class Abstraction ... {
protected Implementor impl;
public void func() ...{
impl.impFunc();
}
}
package bridge;
public class RefinedAbstraction extends Abstraction ... {
public RefinedAbstraction () ...{
this.impl = new ConcreteImplementor();
}
public void func() ...{
super.func();
}
}
package bridge;
public abstract class Implementor ... {
public abstract void impFunc();
}
package bridge;
public class ConcreteImplementor extends Implementor ... {
public void impFunc() ...{
System.out.println(this + ".impFunc()");
}
}
package bridge;
public class Client ... {
public static void main(String[] args) ...{
(new RefinedAbstraction()).func();
}
}