因为这个模式网上有很多不恰当的例子,这里先引用百度百科的定义:桥接模式是将抽象部分与它的实现部分分离,使它们都可以独立地变化。它是一种对象结构型模式,又称为柄体(Handle and Body)模式或接口(Interface)模式。
所以说桥接模式就是接口模式,一方调用接口,一方实现接口。还是百度上的示例代码:
public class Bridge {
interface Implementor {//这里是抽象部分
void Operation();
}
public static class RefinedAbstraction {//可以对这个再继承一个接口
private Implementor implementor;
public void setImplementor(Implementor implementor) {
this.implementor = implementor;
}
public void Operation() {
implementor.Operation();
}
}
static class ConcreteImplementorA implements Implementor {
public void Operation() {
System.out.println("ConcreteImplementorA Operation");
}
}
static class ConcreteImplementorB implements Implementor {
public void Operation() {
System.out.println("ConcreteImplementorB Operation");
}
}
public static void main(String[] args) {
RefinedAbstraction abstraction = new RefinedAbstraction();
abstraction.setImplementor(new ConcreteImplementorA());
abstraction.Operation();
abstraction.setImplementor(new ConcreteImplementorB());//A和B的实现不同
abstraction.Operation();
}
}
输出:
ConcreteImplementorA Operation
ConcreteImplementorB Operation
看网上的很多例子,可能为了把事情说清楚,举得都是很平常的例子。但代码很复杂。其实我们只要知道这就是接口模式,我们就像平时用接口一样用就行了。其实面向对象有两个阶段,一是会用继承,第二就是会用接口。
觉得容易理解的话面向对象的23种设计模式点这里