適配器模式
來(lái)源:程序員人生 發(fā)布時(shí)間:2015-01-05 08:49:10 閱讀次數(shù):4067次
1,不知道大家有無(wú)買過(guò)電子產(chǎn)品,港貨的那中充電的時(shí)候是不符合大陸插頭的我們就需要買1個(gè)轉(zhuǎn)換器給它轉(zhuǎn)換,或變壓器甚么的,將電壓變低或變高,適配器就是這功能
2,沒(méi)甚么好解釋的,直接代碼吧:
// 適配器模式.cpp : 定義控制臺(tái)利用程序的入口點(diǎn)。
//
#include "stdafx.h"
#include <iostream>
#include <string>
using namespace std;
class Player
{
public:
string name;
Player(string name) :name(name){};
virtual void attach() = 0;
virtual void defence() = 0;
};
class Forword :public Player{
public:
Forword(string name) : Player(name){};
void attach(){
cout << name<<"forword attach"<<endl;
}
void defence(){
cout << name << "forword defence" << endl;
}
};
class Center :public Player{
public:
Center(string name) :Player(name){}
void attach(){
cout << name << "Center attach" << endl;
}
void defence(){
cout << name << "Center defence" << endl;
}
};
class ForeignCenter{
public:
string name;
ForeignCenter(string name){
this->name = name;
}
void myAttach(){
cout << name << "foreign myattach" << endl;
}
void myDefence(){
cout << name << "foreign myDefence" << endl;
}
};
//適配器
class Traslator :public Player{
private :
ForeignCenter *fc;
public:
Traslator(string name) :Player(name){
fc = new ForeignCenter(name);
}
void attach(){
fc->myAttach();
}
void defence(){
fc->myDefence();
}
};
int _tmain(int argc, _TCHAR* argv[])
{
Player *p1 = new Center("中衛(wèi)");
p1->attach();
p1->defence();
//將姚明轉(zhuǎn)換為外員(本身不是外員哦)
Traslator *t1 = new Traslator("姚明");
t1->attach();
t1->defence();
cin.get();
return 0;
}
3,
適配器模式是1種補(bǔ)救手段,是為了復(fù)用已有類的代碼并且將其適配到客戶端需要的接口上去。如果寫補(bǔ)釘?shù)脑?就需要這個(gè)模式
生活不易,碼農(nóng)辛苦
如果您覺(jué)得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)