设计模式目录
1.类图

对象适配器

类适配器
2.说明
适配器模式:就解决调用接口(Request)和被调用接口(SpecificRequest)不匹配的问题,加一个适配器(Adapter)解决。
模式解释:接口一般有几个元素组成。
1.返回值
2.接口名称
3.输入参数
该模式解决的是接口名称不同的调用问题。
试想,如果输入的参数不同,那怎么办,怎么办?
没办法了,接口参数都不同,就不具备使用的条件了。
接口间调用在上面的3个条件中,只有接口名称是可以变化的。如果返回值或者参数有变化了,那就不具备接口调用的条件了。
2.代码
代码(c++,对象适配器):
#include <iostream>
using namespace std;
#include <string>
// 抽象层
class Target{
public:
virtual void Request()=0;
};
// 具体层
class Adaptee
{
public:
void SpecificRequest()
{
cout<<"Adaptee::SpecificRequest\n";
}
};
class Adapter: public Target
{
public:
virtual void Request(){
Adaptee* adaptee = new Adaptee();
adaptee->SpecificRequest();
}
};
class Client
{
public:
void maisn(){
Target* target = new Adapter();
target->Request();
}
};
//客户端调用
int main()
{
cout<<"适配器模式\n";
Client* c = new Client();
c->maisn();
//看代码不用考虑以下内容
int cin_a;
cin>>cin_a;
return 0;
}
本文深入探讨了适配器模式的原理与应用,通过C++代码示例详细讲解了对象适配器和类适配器的实现方式,帮助读者理解如何解决接口不匹配的问题。
366

被折叠的 条评论
为什么被折叠?



