本文主要是介绍【设计模式】在NBA需要翻译 --- 适配器模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一,概述
适配器模式(有时候也称包装样式或者包装)将一个类的接口适配成用户所期待的。一个适配允许通常因为接口不兼容而不能在一起工作的类工作在一起,做法是将类自己的接口包裹在一个已存在的类中。
二,设配器基本构成
Target:客户期待的接口(可以是具体的或抽象的类)
Adaptee:需要适配的类(用户要调用,但是不能直接调用)
Adapter:设配器(继承用户所期待的Target,然后根据用户期待的接口适配调用真正需要调用的类Adaptee)
#include <iostream>
using namespace std;class Target
{
public:virtual void Request(){cout<<"普通请求"<<endl;}
};class Adaptee
{
public:void SpecificRequest(){cout<<"特殊请求"<<endl;}
};class Adapter : public Target//记住这里是共有继承
{private:Adaptee *adaptee;// = new Adaptee();public:void Request(){adaptee->SpecificRequest();}
};int main()
{Target *target = new Adapter();target->Request();}
三,适配器示例
在NBA,教练用英语布置战术,姚明听不懂,需要翻译给解释听。就是把教练接口用设配器转化成姚明可以听懂的汉语。
#include <iostream>
using namespace std;//篮球运动员class Player{protected:string name;public:Player(string name){this->name = name;}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 Center :public Player{public:Center(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: public:string name;string getName() {return name; }void setName(string value) {this->name = value; }void China_attack(){cout<<"外籍中锋"<<name<<"进攻"<<endl; } void Chian_defence(){cout<<"外籍中锋"<<name<<"防守"<<endl;}}; //翻译者class Translator : public Player{private:ForeignCenter *wjzf;// = new ForeignCenter();public: Translator(string name): Player(name){wjzf = new ForeignCenter();//必须申请对象 wjzf->name = name;}void Attack(){wjzf->China_attack();}void Defense(){wjzf->Chian_defence();}}; int main(){Player *b = new Forwards("巴蒂尔");b->Attack();Player *m = new Guards("麦克格雷迪");m->Attack();//Player ym = new Center("姚明");Player *ym = new Translator("姚明");ym->Attack();ym->Defense();return 0;}
这篇关于【设计模式】在NBA需要翻译 --- 适配器模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!