设计模式(八)桥梁模式(Bridge)
时间: 2023-11-08 18:50:51 浏览: 54
桥梁模式(Bridge)是一种结构型设计模式,它将抽象部分与实现部分分离,使它们可以独立地变化。它通过将抽象类与实现类分开来解耦,从而可以在两者之间建立一个桥梁。
桥梁模式适用于以下情况:
- 当你希望在运行时切换或扩展抽象部分和实现部分时。
- 当你想要避免在抽象部分中使用继承的情况。
在桥梁模式中,抽象部分(Abstraction)定义了抽象类,并且包含了对实现部分(Implementor)的引用。抽象类提供了一组方法或功能,可以通过委派给实现部分来执行。实现部分定义了一组方法,通过这些方法可以实现抽象类中定义的功能。
以下是一个简单的示例来说明桥梁模式的用法:
```java
// 实现部分接口
interface Implementor {
void operationImpl();
}
// 具体实现类A
class ConcreteImplementorA implements Implementor {
public void operationImpl() {
System.out.println("ConcreteImplementorA: operationImpl");
}
}
// 具体实现类B
class ConcreteImplementorB implements Implementor {
public void operationImpl() {
System.out.println("ConcreteImplementorB: operationImpl");
}
}
// 抽象类
abstract class Abstraction {
protected Implementor implementor;
public Abstraction(Implementor implementor) {
this.implementor = implementor;
}
public abstract void operation();
}
// 扩展抽象类
class RefinedAbstraction extends Abstraction {
public RefinedAbstraction(Implementor implementor) {
super(implementor);
}
public void operation() {
System.out.println("RefinedAbstraction: operation");
implementor.operationImpl();
}
}
public class BridgeExample {
public static void main(String[] args) {
Implementor implementorA = new ConcreteImplementorA();
Implementor implementorB = new ConcreteImplementorB();
Abstraction abstractionA = new RefinedAbstraction(implementorA);
abstractionA.operation();
Abstraction abstractionB = new RefinedAbstraction(implementorB);
abstractionB.operation();
}
}
```
输出结果:
```
RefinedAbstraction: operation
ConcreteImplementorA: operationImpl
RefinedAbstraction: operation
ConcreteImplementorB: operationImpl
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)