适配器模式: 将一个类的接口转化为客户希望的另一个接口;adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
#include <iostream>
using namespace std;
class Player {
protected:
string name;
public:
Player(string name) :name(name){};
virtual ~Player(){};
virtual void Attack(){};
virtual void Defense(){};
};
class Forward:public Player {
public:
Forward(string name) : Player(name){}
~Forward(){};
void Attack(){
cout<< "forword attck:"<<name<<endl;
}
void Defense(){
cout<< "forword defence:"<<name<<endl;
}
};
class Center:public Player {
public:
Center(string name) : Player(name){}
~Center(){};
void Attack(){
cout<< "center attck:"<<name<<endl;
}
void Defense(){
cout<< "center defence:"<<name<<endl;
}
};
class ForeignCenter {
private:
string name;
public:
void setname(string name) {this->name = name;}
string getname(){return this->name;}
void Attack(){
cout<< " 进攻:"<<name<<endl;
}
void Defense(){
cout<< "防守:"<<name<<endl;
}
};
class Translator : public Player {
private:
ForeignCenter * wjzf ;
public:
Translator(string name):Player(name){
wjzf = new ForeignCenter();
wjzf->setname(name);
}
~Translator(){
delete wjzf;
}
void Attack(){
wjzf->Attack();
}
void Defense(){
wjzf->Defense();
}
};
void testLesson13(){
Player * b = new Forward("batier");
b->Attack();
Player *m = new Translator("yaoming");
m ->Attack();
}
适配器的使用场景。想使用一个已经存在的类,但如果它的接口,也就是它的方法和你的要求不相同时,就应该考虑适配器模式。
在双方都不太容易修改的时候再使用适配器模式,争取早点重构。不要问题扩大