您的位置:首页 > 编程语言 > C语言/C++

设计模式C++实现十三:适配器模式

2015-05-13 10:45 239 查看
适配器模式(Adapter):将一个类的接口转换成客户希望的另一个接口。使得原本接口不兼容而不能在一个工作的那些类可以一起工作。

使用场景:当系统的数据和行为都正确,但接口不同时,我们可以考虑使用适配器模式来匹配接口。主要应用在希望复用一些存在的类,但是接口又和复用环境要去不同时使用。

#ifndef ADAPTER_H
#define ADAPTTE_H
#include<iostream>
#include<string>
using namespace std;
class Player
{
protected:
string name;
public:
virtual void Attack()=0;
virtual void Defense() = 0;
};

class Forwards :public Player
{
public:
Forwards(string n) {name = n; }
void Attack()
{
cout << "前锋 " << name << " 进攻。\n";
}
void Defense()
{
cout << "前锋 " << name << " 防守。\n";
}
};

class Guards :public Player
{
public:
Guards(string n) { name = n; }
void Attack()
{
cout << "后卫 " << name << " 进攻。\n";
}
void Defense()
{
cout << "后卫 " << name << " 防守。\n";
}
};
class ForeignCenter :public Player
{
friend class Translator;//声明Translator为友元类,专业它就可以访问ForeignCenter里面的信息,即翻译可以和外国球员交流
public:
ForeignCenter(){}
ForeignCenter(string n) { name = n; }
private://声明为私有意味着外籍中锋不能明白教练进攻和防守的意图。
void Attack()
{
cout << "中锋 " << name << " 进攻。\n";
}
void Defense()
{
cout << "中锋 " << name << " 防守。\n";
}
};

class Translator :public Player
{
ForeignCenter Fcenter;
public:
Translator(string n){ Fcenter.name=n; }
void Attack()
{
Fcenter.Attack();
}
void Defense()
{
Fcenter.Defense();
}
};
#endif


#include"Adapter.h"

int main()
{
Guards mc("麦迪");
mc.Attack();
mc.Defense();

Forwards Bt("巴蒂尔");
Bt.Defense();
Bt.Attack();

Translator Meimei("姚明");//声明Meimei是姚明的翻译,当Meimei响应进攻时,就是Meimei告诉姚明要进攻
Meimei.Attack();
Meimei.Defense();

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: