C++模式学习------适配器模式

适配器模式: 适配器模式属于结构型的设计模式,是将一个类的接口转换成使用方希望的另外一个接口,这样使得原本由于接口不兼容而不能一起工作的那些类可以一起工作。

适配器模式有两种:

1.类的适配器:继承不同地类,在适配器类里面实现接口的兼容

 1 class Interface_USB
 2 {
 3 public:
 4     void doInterfaceUSB()
 5     {
 6         cout<<"Interface USB !!!"<<endl;
 7     }
 8 };
 9 
10 class Interface_TYPEC
11 {
12 public:
13     virtual void doPlugin() = 0;
14 };
15 
16 class Interface_Convertor: public Interface_TYPEC,public Interface_USB
17 {
18 public:
19     void doPlugin()
20     {
21         doConvertor();
22         doInterfaceUSB();
23     }
24     void doConvertor()
25     {
26         cout<<"Type-c 转 USB"<<endl;
27     }
28 };
29 
30 int main()
31 {
32     Interface_Convertor* adapter = new Interface_Convertor();
33     adapter->doPlugin();
34     return 0;
35 }

 

2.对象适配器:在类里面new一个被兼容的对象,通过该对象实现接口的兼容。这种模式采用较多,被兼容的对象也可以不在适配器类里面new出来,而通过接口从外部传入,这样适配器就更加灵活。

 1 class Interface_USB
 2 {
 3 public:
 4     void doInterfaceUSB()
 5     {
 6         cout<<"Interface USB !!!"<<endl;
 7     }
 8 };
 9 
10 class Interface_TYPEC
11 {
12 public:
13     virtual void doPlugin() = 0;
14 };
15 
16 class Interface_Convertor: public Interface_TYPEC
17 {
18 public:
19     void doPlugin()
20     {
21         doConvertor();
22         m_usb.doInterfaceUSB();
23     }
24     void doConvertor()
25     {
26         cout<<"Type-c 转 USB"<<endl;
27     }
28     Interface_USB m_usb;
29 };
30 
31 int main()
32 {
33     Interface_Convertor* adapter = new Interface_Convertor();
34     adapter->doPlugin();
35     return 0;
36 }

 

posted @ 2018-03-30 15:24  漆天初晓  阅读(118)  评论(0编辑  收藏  举报