设计模式使用场景实现示例及优缺点(结构型模式——桥接模式)
结构型模式
桥接模式(Bridge Pattern)
桥接模式(Bridge Pattern)是一种结构型设计模式,其主要目的是“将抽象与实现解耦,使得两者可以独立地变化”。这种模式通过提供抽象化和实现化之间的桥接结构,来实现两者的解耦。
适用场景
-
独立变化:
- 当想要抽象和实现部分可以独立变化时,可以使用桥接模式。
-
多维度变化:
- 当一个类存在两个独立变化的维度,且这两个维度都需要进行扩展时。
-
不希望使用继承:
- 当不希望使用继承或因为多层继承导致系统类的个数急剧增加时。
实现示例(Java)
以下是一个简单的桥接模式的实现示例,展示如何将抽象部分和实现部分进行解耦。
1. 定义实现部分的接口
public interface Implementor {void operationImpl();
}
2. 定义具体实现类
public class ConcreteImplementorA implements Implementor {public void operationImpl() {System.out.println("ConcreteImplementorA: operationImpl");}
}public class ConcreteImplementorB implements Implementor {public void operationImpl() {System.out.println("ConcreteImplementorB: operationImpl");}
}
3. 定义抽象部分的类
public abstract class Abstraction {protected Implementor implementor;protected Abstraction(Implementor implementor) {this.implementor = implementor;}public abstract void operation();
}
4. 定义具体抽象类
public class RefinedAbstraction extends Abstraction {protected RefinedAbstraction(Implementor implementor) {super(implementor);}public void operation() {System.out.println("RefinedAbstraction: operation");implementor.operationImpl();}
}
5. 客户端代码
public class Client {public static void main(String[] args) {Implementor implementorA = new ConcreteImplementorA();Abstraction abstractionA = new RefinedAbstraction(implementorA);abstractionA.operation();Implementor implementorB = new ConcreteImplementorB();Abstraction abstractionB = new RefinedAbstraction(implementorB);abstractionB.operation();}
}
注释说明
-
实现部分的接口:
Implementor
接口定义了实现部分的接口,这个接口通常包含一些基本操作。
-
具体实现类:
ConcreteImplementorA
和ConcreteImplementorB
类实现了Implementor
接口,表示具体的实现。
-
抽象部分的类:
Abstraction
类定义了抽象部分的接口,它持有一个Implementor
对象,并定义了一个抽象方法operation
。
-
具体抽象类:
RefinedAbstraction
类继承了Abstraction
类,它实现了operation
方法,并在这个方法中调用了Implementor
的方法。
-
客户端代码:
Client
类分别创建了ConcreteImplementorA
和ConcreteImplementorB
的对象,并使用这些对象创建了RefinedAbstraction
的对象,然后调用了operation
方法。
优点
-
分离抽象和实现:
- 桥接模式分离了抽象部分和实现部分,使得两者可以独立地进行变化。
-
提高扩展性:
- 桥接模式提高了系统的扩展性,可以独立地扩展抽象部分或实现部分。
-
实现细节对客户透明:
- 桥接模式隐藏了具体的实现细节,客户端只需要关心抽象部分。
缺点
-
增加系统的理解和设计难度:
- 由于抽象部分和实现部分分离,这使得设计比较复杂,理解和设计难度增加。
-
需要正确识别出系统中两个独立变化的维度:
- 对于两个独立变化的维度,其识别的正确性直接决定了桥接模式的使用效果。如果识别错误,那么系统的维护将会变得非常复杂。
类图
Abstraction <---- RefinedAbstraction^|
Implementor <---- ConcreteImplementorA/B
总结
桥接模式通过将抽象部分和实现部分进行解耦,使得两者可以独立地进行变化。这种模式适用于当一个类存在两个独立变化的维度,且这两个维度都需要进行扩展时。尽管桥接模式增加了系统的设计复杂度,但是它提高了系统的扩展性,使得系统的维护和修改更加灵活。