Repository navigation
Expand file tree
/
Copy pathAdapter.cpp
More file actions
87 lines (76 loc) · 2.23 KB
/
Copy pathAdapter.cpp
File metadata and controls
87 lines (76 loc) · 2.23 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
#include <iostream>
#include <algorithm>
#include <memory>
/**
* The Target defines the domain-specific interface used by the client code.
*/
class Target {
public:
virtual ~Target(){
std::cout << "Target destroyed" << std::endl;
};
virtual std::string Request() const {
return "Target: The default target's behavior.";
}
};
/**
* The Adaptee contains some useful behavior, but its interface is incompatible
* with the existing client code. The Adaptee needs some adaptation before the
* client code can use it.
*/
class Adaptee {
public:
~Adaptee()
{
std::cout << "Adaptee destroyed" << std::endl;
};
std::string SpecificRequest() const {
return ".eetpadA eht fo roivaheb laicepS";
}
};
/**
* The Adapter makes the Adaptee's interface compatible with the Target's
* interface.
*/
class Adapter : public Target {
private:
const std::unique_ptr<Adaptee>& adaptee_;
public:
Adapter(const std::unique_ptr<Adaptee>& adaptee) : adaptee_(adaptee) {}
std::string Request() const override {
std::string to_reverse = this->adaptee_->SpecificRequest();
std::reverse(to_reverse.begin(), to_reverse.end());
return "Adapter: (TRANSLATED) " + to_reverse;
}
~Adapter()
{
std::cout << "Adapter destroyed" << std::endl;
};
};
/**
* The client code supports all classes that follow the Target interface.
*/
void ClientCode(const std::unique_ptr<Target>& target) {
std::cout << target->Request();
}
int main() {
std::cout << "Client: I can work just fine with the Target objects:\n";
//Target *target = new Target;
std::unique_ptr<Target> target = std::make_unique<Target>();
ClientCode(target);
std::cout << "\n\n";
//Adaptee *adaptee = new Adaptee;
std::unique_ptr<Adaptee> adaptee = std::make_unique<Adaptee>();
std::cout << "Client: The Adaptee class has a weird interface. See, I don't understand it:\n";
std::cout << "Adaptee: " << adaptee->SpecificRequest();
std::cout << "\n\n";
std::cout << "Client: But I can work with it via the Adapter:\n";
//Adapter *adapter = new Adapter(adaptee);
std::unique_ptr<Target> adapter = std::make_unique<Adapter>(adaptee);
ClientCode(adapter);
std::cout << "\n";
//delete target;
//delete adaptee;
//delete adapter;
return 0;
}