一、意图
将一个类的接口转换为另一个用户希望的接口。Adapter模式使得由于接口不兼容的类可以一起工作。
二、UML
对于类适配器,C++可以使用多继承完成,即对Target使用public继承,对Adaptee使用private继承;在其他语言中则可以选择将Adaptee作为private成员变量使用。
三、示例
#include <iostream>
#include <map>
#include <memory>
class Target
{
public:
virtual ~Target() = default;
virtual std::string Request() const
{
return "Target";
}
};
class Adaptee
{
public:
std::string SpecificRequest() const
{
return "Adaptee";
}
};
// 类适配器
class ClassAdapter : public Target, private Adaptee
{
public:
ClassAdapter() : Target(), Adaptee() {}
std::string Request() const override
{
return "ClassAdapter + " + this->SpecificRequest();
}
};
// 对象适配器
class ObjectAdapter : public Target
{
private:
Adaptee* adaptee;
public:
ObjectAdapter(Adaptee* p_adaptee) : Target()
{
adaptee = p_adaptee;
}
std::string Request() const override
{
return "ObjectAdapter + " + adaptee->SpecificRequest();
}
};
void Cilent(const Target* p_target)
{
std::cout << p_target->Request() << std::endl;
}
int main()
{
Target* myTarget = new Target();
Adaptee* myAdaptee = new Adaptee();
ClassAdapter* classAdapter = new ClassAdapter();
ObjectAdapter* objectAdapter = new ObjectAdapter(myAdaptee);
Cilent(myTarget);
Cilent(classAdapter);
Cilent(objectAdapter);
return 0;
}
Comments | NOTHING