标签:style blog http io ar color os 使用 sp
适配器模式(Adapter),将一个类的接口转换成客户希望的另外一个接口。Adapter模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。
适配器模式结构图如下所示:
图 01 适配器模式结构图
1 #include "iostream" 2 using namespace std; 3 4 class Target 5 { 6 public: 7 virtual void Request() = 0; 8 virtual ~Target() 9 { 10 11 } 12 }; 13 14 class Adaptee 15 { 16 public: 17 void SpecificRequest() 18 { 19 cout << "特殊请求" << endl; 20 } 21 virtual ~Adaptee() 22 { 23 24 } 25 }; 26 27 class Adapter : public Target 28 { 29 private: 30 Adaptee* adaptee; 31 public: 32 Adapter() 33 { 34 adaptee = new Adaptee(); 35 } 36 37 public: 38 virtual void Request() 39 { 40 adaptee->SpecificRequest(); 41 } 42 43 virtual ~Adapter() 44 { 45 if(adaptee != NULL) 46 { 47 delete adaptee; 48 adaptee = NULL; 49 } 50 } 51 }; 52 53 void main() 54 { 55 Target* target = new Adapter(); 56 target->Request(); 57 }
① 需要的东西在面前,但却不能使用,而短时间又无法改造它,于是我们就想办法适配它。
② 在软件的开发过程中,系统的数据和行为都正确,但接口不符时,我们应该考虑用适配器,目的是使控制范围之外的一个原有对象与某个接口匹配。适配器模式主要应用于希望用一些现存的类。但是接口又与复用环境要求不一致的情况,比如在需要对早期代码复用一些功能等应用上很有实际价值。
③ 我们通常是在软件开发后期或维护期再考虑使用适配器模式。
④ 双方都不太容易修改的时候使用适配器模式适配。
图 02 适配器模式实例应用类图
1 #include "iostream" 2 using namespace std; 3 #include <string> 4 5 // 外部需要调用的接口,客户端调用的接口 6 class CPlayer 7 { 8 private: 9 string name; 10 public: 11 CPlayer(string name) 12 { 13 this->name = name; 14 } 15 virtual void Attack() = 0; 16 virtual void Defence() = 0; 17 virtual ~CPlayer() 18 { 19 20 } 21 }; 22 23 // 现在拥有的接口 24 class CForeignCenter 25 { 26 private: 27 string name; 28 public: 29 string GetName() 30 { 31 return this->name; 32 } 33 34 void SetName(string name) 35 { 36 this->name = name; 37 } 38 39 // 姚明需要的是中文的进攻 40 void Jingong() 41 { 42 cout << "外籍中锋" << this->name << "进攻" << endl; 43 } 44 // 姚明需要的是中文的防守 45 void Fangshou() 46 { 47 cout << "外籍中锋" << this->name << "防守" << endl; 48 } 49 }; 50 51 // 适配器,将现在拥有的接口转为需要的接口 52 class CTranslator : public CPlayer 53 { 54 private: 55 CForeignCenter* fc; 56 public: 57 CTranslator(string name) : CPlayer(name) 58 { 59 fc = new CForeignCenter(); 60 } 61 62 virtual void Defence() 63 { 64 fc->Fangshou(); 65 } 66 67 68 virtual void Attack() 69 { 70 fc->Jingong(); 71 } 72 virtual ~CTranslator() 73 { 74 75 } 76 }; 77 78 void main() 79 { 80 CPlayer* ym = new CTranslator("姚明"); 81 ym->Attack(); 82 ym->Defence(); 83 }
2014-12-03 16:48:08
标签:style blog http io ar color os 使用 sp
原文地址:http://www.cnblogs.com/xiaoheike/p/4140460.html