C++ 适配器模式
时间: 2023-06-29 08:04:25 浏览: 70
适配器模式是一种结构型设计模式,它允许你将不兼容的对象包装在一个适配器中,以使其与另一个类兼容。
在 C++ 中,适配器模式可以通过类适配器和对象适配器来实现。
类适配器使用多重继承来实现适配器和目标类的接口之间的转换。适配器类继承目标类和适配器接口类,并实现适配器接口类的方法,将目标类的方法转换为适配器接口类的方法。
例如,假设我们有一个 `Target` 类和一个 `Adaptee` 类,它们的接口不兼容。我们可以创建一个 `Adapter` 类,它继承 `Target` 类并实现 `Adaptee` 类的方法,将 `Adaptee` 类的方法转换为 `Target` 类的方法。
```c++
class Target {
public:
virtual void request() = 0;
};
class Adaptee {
public:
void specificRequest() {
std::cout << "Adaptee specific request" << std::endl;
}
};
class Adapter : public Target, private Adaptee {
public:
void request() override {
specificRequest();
}
};
```
对象适配器使用组合来实现适配器和目标类的接口之间的转换。适配器类包含一个目标类的实例,并实现适配器接口类的方法,将目标类的方法转换为适配器接口类的方法。
例如,我们可以创建一个 `Adapter` 类,它包含一个 `Adaptee` 类的实例,并实现 `Target` 类的方法,将 `Target` 类的方法转换为 `Adaptee` 类的方法。
```c++
class Adapter : public Target {
public:
Adapter(Adaptee* adaptee) : m_adaptee(adaptee) {}
void request() override {
m_adaptee->specificRequest();
}
private:
Adaptee* m_adaptee;
};
```
使用适配器模式可以使我们在不修改现有代码的情况下,将旧接口转换为新接口,从而使不兼容的类能够协同工作。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![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)