码迷,mamicode.com
首页 > 其他好文 > 详细

设计模式14——适配器模式

时间:2014-09-21 15:26:30      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   io   os   ar   2014   div   

适配器模式可以使接口不相同的几个对象通过适配来统一接口。Target与Adaptee各自拥有自己的方法,但接口不同,可以通过Adapter进行统一。

bubuko.com,布布扣

 1 #ifndef Adapter_H_H
 2 #define Adapter_H_H
 3 
 4 #include <iostream>
 5 using namespace std;
 6 
 7 class Target
 8 {
 9 public:
10     virtual void display() { cout << "This is a common target!" << endl; }
11     virtual ~Target() {}
12 };
13 
14 class Adaptee
15 {
16 public:
17     void specialDisplay() { cout << "This is a special target!" << endl; }
18 };
19 
20 class Adapter : public Target
21 {
22 public:
23     Adapter() : adaptee(new Adaptee()) {}
24     virtual void display() { adaptee->specialDisplay(); }
25     ~Adapter() { delete adaptee; }
26 
27 private:
28     Adaptee *adaptee;
29 };
30 
31 
32 void AdapterTest()
33 {
34     Target *target1 = new Target();
35     Target *target2 = new Adapter();
36 
37     target1->display();
38     target2->display();
39 
40     delete target1;
41     delete target2;
42 }
43 
44 
45 #endif

运行结果:

bubuko.com,布布扣

Adaptee与Target接口不同,却可以通过Adapter进行统一。

设计模式14——适配器模式

标签:style   blog   http   color   io   os   ar   2014   div   

原文地址:http://www.cnblogs.com/MiniHouse/p/3984528.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!