C++设计模式之适配器模式

对象适配器有以下特点:

  1. 有的时候,你会发现,不是很容易去构造一个Adaptee类型的对象;
  2. 当Adaptee中添加新的抽象方法时,Adapter类不需要做任何调整,也能正确的进行动作;
  3. 可以使用多肽的方式在Adapter类中调用Adaptee类子类的方法。

代码实现:

 1 // Adapter.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #include<string>
 7 using namespace std;
 8 
 9 
10 class Target
11 {
12 public:
13     Target(){}
14     virtual ~Target(){}
15     virtual void Request()
16     {
17         cout << "Target::Request" << endl;
18     }
19 };
20 class Adaptee
21 {
22 public:
23     void SpecificRequest()
24     {
25         cout << "Adaptee::SpecificRequest" << endl;
26     }
27 };
28 
29 class Adapter : public Target
30 {
31 public:
32     Adapter() : m_Adaptee(new Adaptee) {}
33     ~Adapter()
34     {
35         if (m_Adaptee != NULL)
36         {
37             delete m_Adaptee;
38             m_Adaptee = NULL;
39         }
40     }
41     void Request()
42     {
43         m_Adaptee->SpecificRequest();
44     }
45 
46 private:
47     Adaptee *m_Adaptee;
48 };
49 int _tmain(int argc, _TCHAR* argv[])
50 {
51     cout<<"适配器模式:"<<endl;
52     Target *targetObj = new Adapter();
53     targetObj->Request();
54     delete targetObj;
55     targetObj = NULL;
56     system("pause");
57     return 0;
58 }

猜你喜欢

转载自www.cnblogs.com/wxmwanggood/p/9289233.html