桥接模式
桥接模式
如果某个类存在两个独立变化的维度,通过桥接模式可以使两个维度分离出来,使二者可以独立扩展
角色
- Abstraction(抽象类):定义了抽象类的接口,一般使用抽象类而不是接口实现,其中定义并维护了一个Implementor(实现类接口)对象
- RefinedAbstraction(扩充抽象类):扩充Abatraction所定义的接口,一般情况下是具体类,实现了Abstraction中定义的方法
- Implementor(实现类接口):定义实现类接口
- ConcreteImplementor(具体实现类):不同的实现类提供了基本操作的不同实现
示例代码
//抽象类
public abstract class Abstraction {
protected Implenmentor implenmentor;
public void setImplenmentor(Implenmentor implenmentor) {
this.implenmentor = implenmentor;
}
public abstract void seetings();
}
//扩充实现类1
public class RefinedAbstraction1 extends Abstraction {
@Override
public void seetings() {
System.out.println("Settings ONE");
}
}
//扩充实现类2
public class RefinedAbstraction2 extends Abstraction {
@Override
public void seetings() {
System.out.println("Settings TWO");
}
}
//实现类接口
public interface Implenmentor {
void doSomething();
}
//具体实现类A
public class ConcreteImplementorA implements Implenmentor {
@Override
public void doSomething() {
System.out.println("Do Something In A");
}
}
//具体实现类B
public class ConcreteImplementorB implements Implenmentor {
@Override
public void doSomething() {
System.out.println("Do Something In B");
}
}
//客户端
public class Client {
public static void main(String[] args) {
Abstraction abstraction = new RefinedAbstraction1();
Implenmentor implenmentor = new ConcreteImplementorA();
abstraction.setImplenmentor(implenmentor);
abstraction.seetings();
abstraction.implenmentor.doSomething();
}
}