-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAdapter.cpp
121 lines (92 loc) · 2.56 KB
/
Adapter.cpp
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
#//============================================================================
// Name : Adapter.h
// Created on : 07.07.2020
// Author : Tokmakov Andrey
// Version : 1.0
// Copyright : Your copyright notice
// Description : Adapter tests
//============================================================================
#include "Adapter.h"
#define interface class
namespace Adapter::Classic {
// Existing environmental temperature sensor class
class FahrenheitSensor {
public:
// Get temperature in degrees Fahrenheit
float getFahrenheitTemp() {
float t = 112.0;
// Some code
return t;
}
};
interface ISensor {
public:
virtual ~ISensor() = default;
virtual float getTemperature() = 0;
};
class Adapter : public ISensor {
private:
std::unique_ptr<FahrenheitSensor> p_fsensor;
public:
Adapter(std::unique_ptr<FahrenheitSensor> fSensor) :
p_fsensor(std::move(fSensor)) {
}
virtual ~Adapter() = default;
public:
virtual float getTemperature() {
return (p_fsensor->getFahrenheitTemp() - 32.0)*5.0 / 9.0;
}
};
void Test() {
std::unique_ptr<FahrenheitSensor> fSensor = std::make_unique<FahrenheitSensor>();
std::shared_ptr<ISensor> sensor = std::make_shared<Adapter>(std::move(fSensor));
std::cout << "Celsius temperature = " << sensor->getTemperature() << std::endl;
}
}
namespace Adapter::PrivateInheritance {
// Existing environmental temperature sensor class
class FahrenheitSensor {
private:
float t = 112.0;
public:
// Get temperature in degrees Fahrenheit
float getFahrenheitTemp() {
// Some code
return t;
}
protected:
void adjust(float t) { // Sensor setup (protected method)
this->t = t;
}
};
interface ISensor {
public:
virtual ~ISensor() = default;
virtual float getTemperature() = 0;
virtual void adjust(float t) = 0;
};
class Adapter : public ISensor, private FahrenheitSensor {
public:
Adapter() {
}
virtual ~Adapter() = default;
public:
virtual float getTemperature() {
return (getFahrenheitTemp() - 32.0)*5.0 / 9.0;
}
void adjust(float t) {
FahrenheitSensor::adjust(t);
}
};
void Test() {
std::shared_ptr<ISensor> sensor = std::make_shared<Adapter>();
std::cout << "Celsius temperature = " << sensor->getTemperature() << std::endl;
sensor->adjust(133);
std::cout << "Celsius temperature = " << sensor->getTemperature() << std::endl;
}
}
void Adapter::TEST_ALL()
{
Classic::Test();
// PrivateInheritance::Test();
}