Design Pattern -- Adapter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
// Adapter.cpp : Defines the entry point for the console application.
// author: chillyc
// email: chillycreator @t gmail.com

#include<iostream>
#include<string>
using namespace std;

/// adapter pattern is used for combining two or more classes,
/// which have the same behaviors but different interfaces.
/// some classes is common used in future, and the other which are special will never used.
/// common used classes should be public, and the other is private.
/// some classes which inherit adapter class will never use the special ones.
/// adapter pattern is divided into two patterns.
/// one is belong to class structure, and the other is belong to object structure.

#ifndef INTERFACEA_H
#define INTERFACEA_H
/// Interface A is a common interface!
class Interface_A{
public :
virtual void connect_com();
};
#endif
void Interface_A::connect_com(){
cout<<"connect a"<<endl;
}

#ifndef INTERFACEB_H
#define INTERFACEB_H
/// Interface B is not a common interface,
/// it will be used in some special area!
class Interface_B{
public :
virtual void connect_B();
};
#endif
void Interface_B::connect_B(){
cout<< "connect b"<<endl;
}

#ifndef ADAPTERCLASS_H
#define ADAPTERCLASS_H
/// this class uses private inheritance to construct adapter.
/// and it is a kind of class structure.
class Adapter_Class: public Interface_A, private Interface_B{
public:
Adapter_Class();
~Adapter_Class();
virtual void connect();
};

/// this class uses private member variable to construct adapter.
/// and it uses object relationship.
class Adapter_Object: public Interface_A{
private:
Interface_B * b;
public:
Adapter_Object();
~Adapter_Object();

virtual void connect();
};
#endif

Adapter_Class::Adapter_Class(){
cout<< "Adapter_Class construct"<<endl;

}
Adapter_Class::~Adapter_Class(){}
void Adapter_Class::connect(){
Interface_A::connect_com();
Interface_B::connect_B();
}

Adapter_Object::Adapter_Object(){
cout<<"Adapter_Object construct"<<endl;
b = new Interface_B();

}
Adapter_Object::~Adapter_Object(){
delete b;
}
void Adapter_Object::connect(){
Interface_A::connect_com();
b->connect_B();
}

int main()
{
Adapter_Class ac;
ac.connect();
Adapter_Object ao;
ao.connect();
return 0;
}