桥接模式(Bridge)是一种结构型设计模式。Bridge模式基于类的最小设计原则,通过使用封装、聚合及继承等行为让不同的类承担不同的职责。它的主要特点是把抽象(Abstraction)与行为实现(Implementation)分离开来,从而可以保持各部分的独立性以及应对他们的功能扩展。
桥接模式的角色和职责:
1.Client 调用端
这是Bridge模式的调用者。
2.抽象类(Abstraction)
抽象类接口(接口这货抽象类)维护队行为实现(implementation)的引用。它的角色就是桥接类。
3.Refined Abstraction
这是Abstraction的子类。
4.Implementor
行为实现类接口(Abstraction接口定义了基于Implementor接口的更高层次的操作)
5.ConcreteImplementor
Implementor的子类
桥接模式的UML图如下:
示例代码如下:
首先定义Implementor接口,其中定义了其实现类必须要实现的接口operation()
public interface Implementor {
public void operation();
}
下面定义Implementor接口的两个实现类:
public class ConcreateImplementorA implements Implementor {
@Override
public void operation() {
System.out.println("this is concreteImplementorA's operation...");
}
}
public class ConcreateImplementorB implements Implementor {
@Override
public void operation() {
System.out.println("this is concreteImplementorB's operation...");
}
}
public abstract class Abstraction {
private Implementor implementor;
public Implementor getImplementor() {
return implementor;
}
public void setImplementor(Implementor implementor) {
this.implementor = implementor;
}
protected void operation(){
implementor.operation();
}
}
下面是Abstraction类的子类RefinedAbstraction:
public class RefinedAbstraction extends Abstraction {
@Override
protected void operation() {
super.getImplementor().operation();
}
}
测试:
public class BridgeTest {
public static void main(String[] args) {
Abstraction abstraction = new RefinedAbstraction();
//调用第一个实现类
abstraction.setImplementor(new ConcreateImplementorA());
abstraction.operation();
//调用第二个实现类
abstraction.setImplementor(new ConcreateImplementorB());
abstraction.operation();
}
}
转载:https://www.cnblogs.com/lixiuyu/p/5923160.html