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

发布于:2025-02-12 ⋅ 阅读:(100) ⋅ 点赞:(0)

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

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

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

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

使用场景:

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();
}


网站公告

今日签到

点亮在社区的每一天
去签到