1 #include <iostream>
2 using namespace std;
3
4 class target
5 {
6 public:
7 target(){}
8 virtual ~target(){}
9
10 virtual void Operation(){};
11 };
12
13 class adaptee{
14 public:
15 void special_work(){
16 cout<<"only I can do!!\n";
17 }
18 };
19
20
21 /*类适配器模式
22 * 优点:可以重定义adaptee的部分行为
23 * 缺点:不能匹配adaptee的所有子类*/
24 class adapter: public target,private adaptee
25 {
26 public:
27 virtual void Operation(){adaptee::special_work();}
28 };
29
30 int main()
31 {
32 target* tmp=new adapter();
33 tmp->Operation();
34 return 0;
35 }
1 #include <iostream>
2 using namespace std;
3
4 class target
5 {
6 public:
7 target(){}
8 virtual ~target(){}
9
10 virtual void Operation(){};
11 };
12
13 class adaptee{
14 public:
15 void special_work(){
16 cout<<"only I can do!!\n";
17 }
18 };
19
20
21 /*对象适配器模式
22 * 缺点:很难重新定义adaptee的行为,只能通过生成子类
23 * 优点:一个adapter可以匹配adaptee的所有子类*/
24 class adapter: public target
25 {
26 adaptee* p_adaptee;
27 public:
28 adapter(adaptee* var){
29 p_adaptee=var;
30 }
31 virtual void Operation(){p_adaptee->special_work();}
32 };
33
34 int main()
35 {
36 adaptee* tmp_adaptee=new adaptee();
37 target* tmp=new adapter(tmp_adaptee);
38 tmp->Operation();
39 return 0;
40 }