什么是适配器模式?
将类的接口or函数适配成所需的行为就叫做适配器。
如何更加生动形象的理解这个呢?以手机充电为例子
- 我们在给手机充电时都会用到USB的电源适配器,对外暴漏一个USB的接口
class Charge {
public:
virtual ~Charge() = default;
virtual std::string StartCharge() const { return "this is wan neng chong"; }
};
- 随着智能机的出现,出现了各式各样的接口比如苹果的Lightning安卓的Typec
class AppleCharge {
public:
std::string StartQuickCharge() const { return "this is apple charge"; }
};
但大家都知道智能手机的电池是内置的,那正负极如何连接到电池上呢?。这时候我们想到了数据线(充电线)
- 这时候我们通过数据线进行适配
class AdapterApple : public Charge {
private:
std::shared_ptr<AppleCharge> apple_;
public:
AdapterApple(std::shared_ptr<AppleCharge> apple) : apple_(apple) {}
std::string StartCharge() const override{
std::string apple_charge = this->apple_->StartQuickCharge();
return "Adapter:" + apple_charge + " line";
}
};
这个时候我们充电则没有任何问题,如果购买了安卓的手机,只需要再用TypeC的线与安卓手机连接后放到充电器上适用即可
#include <iostream>
#include <memory>
class Charge;
class AppleCharge;
class AdapterApple;
//class AndroidCharge;//如果未来增加了安卓充电
//class AdapterAndroid;
void GoCharge(const std::shared_ptr<Charge> target)
{
std::cout << target->StartCharge()<<std::endl;
}
int main()
{
std::shared_ptr<Charge> target = std::make_shared<Charge>();
GoCharge(target);
std::shared_ptr<AppleCharge> apple = std::make_shared<AppleCharge>();
std::cout << "charge object: " << apple->StartQuickCharge() << std::endl;
std::shared_ptr<AdapterApple> apple_line = std::make_shared<AdapterApple>(apple);
GoCharge(apple_line);
return 0;
}
适配器在代码中应用的场景
- 在程序架构设计之出,无需考虑使用此模式,适配器模式本身就是打补丁,修修补补;
- 一般用在软件大版本升级之时,旧接口还在用,新老接口又不相同,这时候通过适配器模式把新接口转义成旧接口可识别的;
- 另外一种情况是统一某个功能不同的执行方式。比如你的本地新引入log4cpp和glog两种来日志库,为了测试用户不同机器上写日志的效果,这时候旧需要一个适配器模式来保证传进来的参数和打印log的模板一致
- 适配器的核心:就是根据现有已有的功能,重载已经存在的接口,来实现新功能的拓展(一般是:指通过重载后的接口调用新增加业务类的函数)