欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 锐评 > 结构形模式---适配器模式

结构形模式---适配器模式

2026/2/1 20:19:37 来源:https://blog.csdn.net/qq_43812868/article/details/145581594  浏览:    关键词:结构形模式---适配器模式

适配器模式是一种结构形模式,主要用于不同在两个互不兼容的类或者库之间增加一个转换。

适配器模式的实现由两种方式,一种是适配器对象,一种是适配器类。

适配器是对象是将第三方接口通过对象调用引入到适配器中。

适配器类是通过多继承将第三方接口继承到适配器类中。

使用场景:

1、当使用的类与其他接口代码不兼容的时候,可以使用适配器模式。

2、当继承于一个类,这个类的不同子类有不同的方法,这些方法不是这继承体系中所具有的共性问题。基可以使用适配器来实现这些不同的方法。

创建方式:

1、创建两个类,一个是接口类,一个三方类(正常是三方特定类);

2、创建一个继承于接口类的适配器类,这个适配器类接口要和接口类保持一致,在适配器中定义一个三方接口的引用。

3、客户端通过接口类的接口调用三方接口。

类关系结构:
在这里插入图片描述
代码:

#include "ShiPaiQi.h"int main()
{std::cout << "欢迎东哥来到设计模式的世界!\n";NationPhone* nationPhone = new NationPhone();nationPhone->tranframe();cout << "=======================================" << endl;NationPhone* adapteePhone = new AdapteePhone();adapteePhone->tranframe();
}
#pragma once
#include "string.h"
#include "iostream"
using namespace std;
//三方接口
class EngishPhone {
public:EngishPhone();~EngishPhone();void EngishTranframe();};//统一接口
class NationPhone
{
public:EngishPhone _m_EngishPhone;
public:NationPhone();~NationPhone();virtual void  tranframe();
};//适配器
class AdapteePhone : public NationPhone
{
public:AdapteePhone();~AdapteePhone();void  tranframe();
};
#include "ShiPaiQi.h"EngishPhone::EngishPhone()
{
}EngishPhone::~EngishPhone()
{
}void EngishPhone::EngishTranframe()
{cout << "三方转换英语接口" << endl;
}NationPhone::NationPhone()
{
}NationPhone::~NationPhone()
{
}void NationPhone::tranframe()
{cout << "调用基类翻译接口" << endl;
}AdapteePhone::AdapteePhone()
{
}AdapteePhone::~AdapteePhone()
{
}void AdapteePhone::tranframe()
{cout << "调用适配器翻译接口" << endl;_m_EngishPhone.EngishTranframe();
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词