C++ 適配器模式解析
適配器模式概念
- 將一個類的接口,轉換成客戶端期望的另一個接口。適配器讓原先接口不兼容的類可以合作無間。
適配器實例
-
最簡單的示例就是常規3.5mm耳機插入蘋果7以上的手機,需要轉接頭的需求。
很明顯來說,轉接頭需要能繼承於3.5mm耳機,正面又得是蘋果耳機的頭,這就涉及到繼承問題,即轉接頭首先得繼承於正常耳機,後面插入的方式得是蘋果耳機方式。
用適配器模式來表達就很好表達
頭文件:
定義正常耳機,插槽 轉接頭的關係
#include "stdafx.h"
//3.5mm 耳機
class MicroEarPhone
{
public:
virtual void enterMethod(); //插孔方式
};
//蘋果插槽
class IPhoneSlot
{
public:
virtual void beEnterMethod();
};
//耳機轉接頭
//首先需要後面能被3.5mm耳機插,需要繼承
class EarphoneAdapter:public MicroEarPhone
{
public:
EarphoneAdapter(IPhoneSlot * cur_slot);
virtual void enterMethod();
private:
IPhoneSlot* m_IPhone;
};
接下來是實現
//適配器模式實例
//蘋果
#include "stdafx.h"
#include "AdapterMode.h"
using namespace std;
void MicroEarPhone::enterMethod()
{
cout << "這是3.5mm耳機" << endl;
}
void IPhoneSlot::beEnterMethod()
{
cout << "蘋果7的耳機孔" << endl;
}
EarphoneAdapter::EarphoneAdapter(IPhoneSlot * cur_slot)
{
m_IPhone = cur_slot;
}
void EarphoneAdapter::enterMethod()
{
MicroEarPhone::enterMethod();
cout << "使用轉接頭" << endl;
m_IPhone->beEnterMethod();//然後進入正常轉接
}
int _tmain(int argc, _TCHAR* argv[])
{
IPhoneSlot * cur_iphone = new IPhoneSlot();
MicroEarPhone * cur_ear = new EarphoneAdapter(cur_iphone);
cur_ear->enterMethod();
delete cur_ear;
delete cur_iphone;
system("pause");
return 0;
}
運行結果:
所以很容易的看出實現了適配器模式。