大话设计模式17----适配器模式
2016-07-24 17:21
1046 查看
大话设计模式
1 适配器模式结构图
2 对适配器模式的一些解释
概念:将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。【DP】使用场景:
在想使用一个已存在的类,但是如果他的接口,也就是它的方法和你的要求不相同时,就应该考使用场景。
用了适配器模式,客户代码可以统一调用统一接口就行了,这样可以更简单,更直接,更紧凑。
要在双方都不太容易修改的时候再使用适配器模式适配,而不是一有不同是就使用它。
3 C++源代码实现
1 代码结构图
2 C++代码
#include<iostream> #include<string> using std::cout; using std::endl; using std::string; class Player { protected: string name; public: Player(string name) { this->name = name; } string getName() { return this->name; } void setName(string name) { this->name = name; } virtual void Attack() { cout << "进攻!" << endl; } virtual void Defense() { cout << "防守" << endl; } }; class Forwards:public Player { public: Forwards(string name) :Player(name){} void Attack() override { cout << "前锋 " << getName() << ":进攻!!!" << endl; } void Defense() override { cout << "前锋 " << getName() << "防守!!!" << endl; } }; class Center :public Player { public: Center(string name) :Player(name){} void Attack() override { cout << "中锋 " << getName() << ":进攻!!!" << endl; } void Defense() override { cout << "中锋 " << getName() << "防守!!!" << endl; } }; class Guards :public Player { public: Guards(string name) :Player(name){} void Attack() override { cout << "后卫 " << getName() << ":进攻!!!" << endl; } void Defense() override { cout << "后卫 " << getName() << "防守!!!" << endl; } }; class ForeignCenter { private: string name; public: void setName(string name) { this->name = name; } string getName() { return this->name; } void 进攻() { cout << "外籍中锋 " << getName() << ":进攻!!!" << endl; } void 防守() { cout << "外籍中锋 " << getName() << ":防守!!!" << endl; } }; class Translator :public Player { private: ForeignCenter *foreign; public: Translator(string name) :Player(name) { foreign = new ForeignCenter(); foreign->setName(name); } ~Translator() { delete foreign; foreign = nullptr; } void Attack() override { foreign->进攻(); } void Defense() override { foreign->防守(); } }; int main() { Player *b = new Forwards("巴蒂尔"); b->Attack(); b->Defense(); Player *c = new Center("麦克格雷迪"); c->Attack(); c->Defense(); Player *ym = new Translator("姚明"); ym->Attack(); ym->Defense(); system("pause"); return 0; }
运行结果:
前锋 巴蒂尔:进攻!!! 前锋 巴蒂尔防守!!! 中锋 麦克格雷迪:进攻!!! 中锋 麦克格雷迪防守!!! 外籍中锋 姚明:进攻!!! 外籍中锋 姚明:防守!!! 请按任意键继续. . .
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- 解析C#设计模式编程中适配器模式的实现
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++高级程序员成长之路
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C++的template模板中class与typename关键字的区别分析