由于网络上介绍设计模式的文章要么废话太多不讲要领,要么太细致入微,没有精力看,一番挣扎后,把比较好的介绍放在【设计模式】系列进行精要总结,以C++代码为例。文档内容主要参考《深入设计模式》一书。所有设计模式均可先看意图和示例代码。
本文介绍结构型模式之-适配器模式
意图
适配器模式是一种结构型设计模式, 它能使接口不兼容的对象能够相互合作。
应用场景
1. 希望使用某个类或功能,但其接口与已有框架代码不兼容时,可以使用适配器类
比如C++工程中希望调用sqlite3的接口,可以实现这样一个类SqliteService,封装sql语句,提供给上层业务调用。
实现方式
可看过示例代码后再回头读
- 确保至少有两个类的接口不兼容:
- 一个无法修改 (通常是第三方、 遗留系统或者存在众多已有依赖的类) 的功能性服务类。
- 一个或多个将受益于使用服务类的客户端类。
- 声明客户端接口, 描述客户端如何与服务交互。
- 创建遵循客户端接口的适配器类。 所有方法暂时都为空。
- 在适配器类中添加一个成员变量用于保存对于服务对象的引用。 通常情况下会通过构造函数对该成员变量进行初始化, 但有时在调用其方法时将该变量传递给适配器会更方便。
- 依次实现适配器类客户端接口的所有方法。 适配器会将实际工作委派给服务对象, 自身只负责接口或数据格式的转换。
- 客户端必须通过客户端接口使用适配器。 这样一来, 你就可以在不影响客户端代码的情况下修改或扩展适配器。
代码示例
#include <iostream>
#include <string>
#include <algorithm>
#include <cctype>
class Adaptee{
private:
const std::string string = "string from adptee";
public:
// Adaptee() : string("This can only get from Adaptee!") {}
~Adaptee(){}
std::string Request() const {
return string;
}
};
class ClientTarget{
public:
virtual ~ClientTarget(){}
virtual std::string Request() const {
return "Request from ClientTarget, it's for client\n";
}
};
class Adaptor : public ClientTarget{
private:
Adaptee* adptee_;
public:
Adaptor(Adaptee* adp):adptee_(adp){}
virtual std::string Request() const override {
std::string result = adptee_->Request();
std::transform(result.begin(), result.end(), result.begin(),
[](unsigned char c) { return std::toupper(c); }); //业务处理,全转为大写
return result;
}
};
void ClientCode(ClientTarget* target){
std::cout<<target->Request()<<std::endl;
}
int main(){
std::cout<<"Client can only cooperate with ClientTarget:\n";
ClientTarget* normal_target = new ClientTarget();
ClientCode(normal_target);
std::cout<<"ClientCode cannot cooperate with Adaptee, but can work through by Adaptor\n";
Adaptee* adaptee = new Adaptee();
Adaptor* adaptor = new Adaptor(adaptee);
ClientCode(adaptor);
delete normal_target;
delete adaptee;
delete adaptor;
return 0;
}
关于代码的意思,看一眼输出即明了:
Client can only cooperate with ClientTarget:
Request from ClientTarget, it's for client
ClientCode cannot cooperate with Adaptee, but can work through by Adaptor
STRING FROM ADPTEE
适配器模式较简单,不做更多说明。但工程中很常用。
相比其他知识点,设计模式更重在理解而非记忆,(八股文会被但不会用的一大堆)不易考察,但是是程序员的内功之一。
参考文献
【1】https://refactoringguru.cn/design-patterns/adapter