Henkk

导航

设计模式学习之----适配器模式

适配器模式

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

   适配器类中聚合自定义类的对象。

 1 #include <iostream>
 2 #include <string>
 3 #include <list>
 4 
 5 using namespace std;
 6 class Current18V
 7 {
 8 public:
 9     virtual void useCurrent18V() = 0;
10 };
11 
12 class Current220V
13 {
14 public:
15     void useCurrent120V()
16     {
17         cout << "I am 120V" << endl;
18     }
19 
20 };
21 
22 //主流程操作对象
23 class Adapter : public Current18V
24 {
25 public:
26     Adapter(Current220V* current)
27     {
28         m_current = current;
29 
30     }
31     virtual void useCurrent18V()
32     {
33         m_current->useCurrent120V();
34     }
35 
36 private:
37     Current220V* m_current; //聚合方式包含要适配的类型
38 };
39 
40 
41 
42 int main()
43 {
44     Current220V *current220 = new Current220V;
45 
46     Adapter *adapter = new Adapter(current220);
47     adapter->useCurrent18V();
48 
49     delete current220;
50     delete adapter;
51 
52     return system("pause");
53 }

 

posted on 2020-05-22 11:41  Henkk  阅读(117)  评论(0编辑  收藏  举报