【C++】【设计模式】适配器模式(Adapter Pattern)
定义
- 结构型模式
- 当现有的类提供的接口不是客户端所需要的情况,用适配器模式定义包装类。包装不兼容的对象。达到将一个接口转换成客户希望的另一个接口的目的
结构
UML类图(对象适配器)
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/9a348cf0dc2145c1bb2517bc0c4d7bb4.png)
Demo
#include <iostream>
// 第三方游戏引擎的类
class ThirdPartyGameEngine {
public:
void jump() {
std::cout << "ThirdPartyGameEngine: Jump called.\n";
}
void shoot() {
std::cout << "ThirdPartyGameEngine: Shoot called.\n";
}
};
// 游戏所需的接口
class Game {
public:
virtual ~Game() = default;
virtual void jumpAction() = 0;
virtual void shootAction() = 0;
};
// 适配器
class GameAdapter : public Game {
public:
GameAdapter(ThirdPartyGameEngine* engine) : engine_(engine) {}
void jumpAction() override {
std::cout << "GameAdapter: Jump action called.\n";
engine_->jump();
}
void shootAction() override {
std::cout << "GameAdapter: Shoot action called.\n";
engine_->shoot();
}
private:
ThirdPartyGameEngine* engine_;
};
// 游戏客户端
class GameClient {
public:
GameClient(Game* game) : game_(game) {}
void play() {
std::cout << "GameClient: Play game called.\n";
game_->jumpAction();
game_->shootAction();
}
private:
Game* game_;
};
int main() {
ThirdPartyGameEngine engine;
GameAdapter adapter(&engine);
GameClient client(&adapter);
client.play();
return 0;
}
分析
- 引入适配类将目标和适配类解耦,无需修改原有代码、符合开闭原则
- 增加复用性、拓展性好
- 增加一些复杂性和性能开销
- 能够较好地处理接口不兼容问题