c++ 结构型模式-适配器(Adapter)

1) 意图:

将一个类的接口转换成客户希望的另一个接口。适配器模式使得原本由于接口不兼容而不能一起工作的那些类可以一起工作

2) 结构:

适配器两种结构,一种继承实现,一种组合实现

  a. 继承方式:

  

       b. 组合方式:

   其中:

    1. Target定义Client使用的与特定领域相关的接口
    2. Client与符合Target接口的对象协同
    3. Adaptee定义一个已经存在的接口,这个接口需要适配
    4. AdapterAdaptee的接口与Target接口进行适配

3) 适用性:

  1. 想使用一个类,但是它的接口不符合要求
  2. 想创建一个可以用的类,该类可以和其他不相关的类或不可预见的类协同工作
  3. 想使用一个已经存在的子类,但是不可能对每一个都进行子类化以匹配它们的接口

4) 举例:

  a. 继承方式:

  

 1  #include <iostream>
 2 class  Target
 3 {
 4 public:
 5     Target() {}
 6     virtual ~Target() {}
 7     virtual std::string Request() = 0;
 8 };
 9 
10 class  Adaptee
11 {
12 public:
13     Adaptee() {}
14     virtual ~Adaptee() {}
15     void  SpecificRequest(std::string& str)
16     {
17         str = "Hello World";
18     }
19 };
20 
21 class  Adapter : public Target, public  Adaptee
22 {
23 public:
24     Adapter() {}
25     virtual ~Adapter() {}
26     std::string Request()
27     {
28         std::string str;
29         SpecificRequest(str);
30         return str;
31     }
32 };
33 
34  int main()
35  {
36      Target* target = new Adapter();
37      std::string str = target->Request();
38      std::cout << str.c_str() << std::endl;
39      system("pause");
40  }

  b. 组合方式:

 1 #include <iostream>
 2 class  Target
 3 {
 4 public:
 5     Target() {}
 6     virtual ~Target() {}
 7     virtual std::string Request() = 0;
 8 };
 9 
10 class  Adaptee
11 {
12 public:
13     Adaptee() {}
14     virtual ~Adaptee() {}
15     void  SpecificRequest(std::string& str)
16     {
17         str = "Hello World";
18     }
19 };
20 
21 class  Adapter : public Target
22 {
23 public:
24     Adapter():m_adaptee(NULL){}
25     virtual ~Adapter() 
26     {
27         if (m_adaptee) delete m_adaptee;
28     }
29     std::string Request()
30     {
31         std::string str;
32         m_adaptee = new Adaptee();
33         m_adaptee->SpecificRequest(str);
34         return str;
35     }
36 private:
37     Adaptee* m_adaptee;
38 };
39 
40  int main()
41  {
42      Target* target = new Adapter();
43      std::string str = target->Request();
44      std::cout << str.c_str() << std::endl;
45      system("pause");
46  }

猜你喜欢

转载自www.cnblogs.com/ho966/p/12231094.html
今日推荐