首页 > 代码库 > 适配器模式

适配器模式

1,不知道大家有没有买过电子产品,港货的那中充电的时候是不符合大陆插头的我们就需要买一个转换器给它转换,或者变压器什么的,将电压变低或变高,适配器就是这功能

2,没什么好解释的,直接代码吧:

// 适配器模式.cpp : 定义控制台应用程序的入口点。
//

#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("中卫");
	p1->attach();
	p1->defence();

	//将姚明转换为外员(本身不是外员哦)
	Traslator *t1 = new Traslator("姚明");
	t1->attach();
	t1->defence();

	cin.get();
	return 0;
}
3,适配器模式是一种补救手段,是为了复用已有类的代码并且将其适配到客户端需要的接口上去。如果写补丁的话,就需要这个模式


适配器模式