定义
将俩个维度分离,使他们可以独立变化。又称为柄体(Handle and Body)模式或者接口(interface)模式。
结构图
角色与理解
- 桥接模式包含如下角色:
-
- Abstraction(抽象类):用于定义抽象类的接口,一般为抽象类而不是接口,其中维持一个Implementor的引用
- RefinedAbstraction(扩充抽象类):继承或者实现抽象类,通常情况下为具体类而不是抽象类,实现抽象类中定义的抽象业务方法,在具体业务方法中可以调用Implementor中定义的业务方法
- Implementor(实现类接口):定义实现类的接口,一般而言,Implementor接口仅提供基本操作,并交由子类去实现
- ConcreteImplementor (具体实现类):实现Implementor中定义的基本操作方法
- 抽象类持有实现类接口的对象,调用实现类接口中定义的方法
- 本质上是两个独立变化的维度,一个抽象层引用另一个抽象层的东西,以实现通过实现类进行业务方法的调用
核心代码
抽象类
public abstract class Abstraction {
protected Implementor implementor;
//约束子类必须实现该构造函数
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
//自身的行为和属性
public void operation() {
this.implementor.operationImpl();
}
}
public class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor implementor) {
super(implementor);
}
@Override
public void operation() {
implementor.operationImpl();
}
}
public interface Implementor {
void operationImpl();
}
public class ConcreteImplementor implements Implementor {
@Override
public void operationImpl() {
System.out.println("具体实现的操作!!!");
}
}
客户端
public class Client {
public static void main(String[] args) {
Implementor imp = new ConcreteImplementor();
Abstraction abs = new RefinedAbstraction(imp);
abs.operation();;
}
}