适配器模式(Adapter): 将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
在软件开发中,系统的数据和行为都正确,但接口不符时,我们应该考虑用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望复用一些现存的类,但是接口又与复用环境要求不一致的情况。
基本代码
#include<iostream>
#include<string>
#include<vector>
using namespace std;
//Target(客户所期待的接口。目标可以是具体的或抽象的类,也可以是接口)
class Target
{
public:
virtual void Request()
{
cout << "普通请求!" << endl;
}
};
//Adaptee(需要适配的类)
class Adaptee
{
public:
void SpecificRequest()
{
cout << "特殊请求!" << endl;
}
};
//Adapter(通过在内部包装一个Adapter对象,把源原接口转换成目标接口)
class Adapter :public Target
{
private:
Adaptee* adaptee;
public:
Adapter() :adaptee(new Adaptee()) {}
void Request()
{
adaptee->SpecificRequest();
}
};
int main()
{
Target* target = new Adapter();
target->Request();
system("pause");
return 0;
}
篮球翻译适配器
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Player
{
protected:
string name;
public:
Player(string name_t)
{
name = name_t;
}
virtual void Attack() = 0;
virtual void Defense() = 0;
};
class Forwards :public Player
{
public:
Forwards(string name) : Player(name)
{
}
void Attack()
{
cout << "前锋" << name << "进攻" << endl;
}
void Defense()
{
cout << "前锋" << name << "防守" << endl;
}
};
class Guards :public Player
{
public:
Guards(string name) : Player(name)
{
}
void Attack()
{
cout << "后卫" << name << "进攻" << endl;
}
void Defense()
{
cout << "后卫" << name << "防守" << endl;
}
};
//外籍中锋
class ForeignCenter
{
private:
string name;
public:
string getName() { return name; }
void setName(string name_t) { name = name_t; }
void Jingong()
{
cout << "外籍中锋" << name << "进攻" << endl;
}
void Fangshou()
{
cout << "外籍中锋" << name << "防守" << endl;
}
};
class Translator : public Player
{
private:
ForeignCenter* wjzf;
public:
Translator(string name_t)
: Player(name_t)
{
wjzf = new ForeignCenter();
wjzf->setName(name);
}
void Attack()
{
wjzf->Jingong();
}
void Defense()
{
wjzf->Fangshou();
}
};
int main()
{
Player* b = new Forwards("巴蒂尔");
b->Attack();
Player* m = new Guards("麦迪");
m->Attack();
Player* ym = new Translator("姚明");
ym->Attack();
ym->Defense();
system("pause");
return 0;
}