Repository navigation
Expand file tree
/
Copy pathStructural-AdapterDesignPattern.cpp
More file actions
105 lines (80 loc) · 2.65 KB
/
Copy pathStructural-AdapterDesignPattern.cpp
File metadata and controls
105 lines (80 loc) · 2.65 KB
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
97
98
99
100
101
102
103
104
/*
The Adapter Design pattern allows incompatible classes to work together by converting the interface of one class into another
Example 1:
Consider , my socket(flat pin) is as per the Europe standard however my electric kettle have US based pin(Round) so both are different all to gather however we want to make things work , in that case adapter will come into the picture so we have to create one adapter which will help both the interface to work together.
*/
#include <iostream>
typedef int Cable; // wire with electrons :-)
/* Adaptee (source) interface */
class EuropeanSocketInterface
{
public:
virtual int voltage() = 0;
virtual Cable live() = 0;
virtual Cable neutral() = 0;
virtual Cable earth() = 0;
};
/* Adaptee */
class Socket : public EuropeanSocketInterface
{
public:
int voltage() { return 230; }
Cable live() { return 1; }
Cable neutral() { return -1; }
Cable earth() { return 0; }
};
/* Target interface */
class USASocketInterface
{
public:
virtual int voltage() = 0;
virtual Cable live() = 0;
virtual Cable neutral() = 0;
};
/* The Adapter */
class Adapter : public USASocketInterface
{
EuropeanSocketInterface* socket;
public:
void plugIn(EuropeanSocketInterface* outlet)
{
socket = outlet;
}
int voltage() { return 110; }
Cable live() { return socket->live(); }
Cable neutral() { return socket->neutral(); }
};
/* Client */
class ElectricKettle
{
USASocketInterface* power;
public:
void plugIn(USASocketInterface* supply)
{
power = supply;
}
void boil()
{
if (power->voltage() > 110)
{
std::cout << "Kettle is on fire!" << std::endl;
return;
}
if (power->live() == 1 && power->neutral() == -1)
{
std::cout << "Coffee time!" << std::endl;
}
}
};
int main()
{
Socket* socket = new Socket;
Adapter* adapter = new Adapter;
ElectricKettle* kettle = new ElectricKettle;
/* Pluging in. */
adapter->plugIn(socket);
kettle->plugIn(adapter);
/* Having coffee */
kettle->boil();
return 0;
}