图片引用于菜鸟教程
简介:把某个类的接口通过适配器类引用到是适配类里从而实现兼容
优点:解决目标接口和适配类接口不一致的问题,提高了类的复用性
缺点:降低了代码的阅读性,过多的适配器类会导致系统代码凌乱
例子背景:现在有2个类,一个类的接口为ShowWithAdd,一个类为printAdd,现在需要他俩兼容,于是使用了适配器
适配器模式代码:
- 目标类:
#pragma once
#include <iostream>
#include <string>
using namespace std;
class Target
{
public:
Target(const string& str) : m_str(str){}
virtual ~Target() {}
void ShowWithAdd()
{
cout << "+" << m_str << "+" << endl;
}
void ShowWithMinus()
{
cout << "-" << m_str << "-" << endl;
}
private:
string m_str;
};
- 需要适配的类:
class Adaptee
{
public:
virtual ~Adaptee() {}
virtual void printAdd() = 0;
virtual void printMinus() = 0;
};
- 适配器类:
#pragma once
#include "Adaptee.h"
#include "Target.h"
class Adapter : public Adaptee, public Target
{
public:
Adapter(const string& str) : Target(str){}
virtual void printAdd()
{
ShowWithAdd();
}
virtual void printMinus()
{
ShowWithMinus();
}
};
- 引用:
#include "Adapter.h"
int main()
{
shared_ptr<Adapter> adapter(new Adapter("HelloWorld"));
adapter->printAdd();
adapter->printMinus();
getchar();
return 0;
}
总结:
适配器模式(Adapter):可以通过适配器类去解释原有的类,再开放新的接口给客户端,实现复用性,增加代码灵活性。
作者:丶梦爱
博客:https://blog.youkuaiyun.com/u014732297(转载请说明出处)