-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmemento.cpp
83 lines (73 loc) · 1.86 KB
/
memento.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
/*!
* \brief Memento. Without violating encapsulation,capture
* and externalize an object's internal state so that the
* object can be restored to this state later.
*
*/
#include <iostream>
// Memento. Responsible for storing the internal state of the Originator
// and providing the internal state of the Originator as needed.
class Memento {
public:
Memento(const std::string& state) {
this->state_ = state;
}
void SetState(const std::string& state) {
this->state_ = state;
}
std::string &GetState() {
return this->state_;
}
private:
std::string state_;
};
// Originator. It is responsible for recording the internal state of the
// current moment, defining which states belong to the backup scope,
// and creating and restoring the memo data.
class Originator {
public:
Originator(const std::string& state) {
this->state_ = state;
}
Memento* CreateMemento() {
return new Memento(this->state_);
}
void RestoreToMemento(Memento* memento) {
this->state_ = memento->GetState();
}
void SetState(const std::string& state) {
this->state_ = state;
}
std::string &GetState() {
return this->state_;
}
private:
std::string state_;
};
// Caretaker. Manage, save and provide the Memento.
class Caretaker {
public:
void SetMemento(Memento* memento) {
this->memento_ = memento;
}
Memento* GetMemento() {
return this->memento_;
}
private:
Memento* memento_;
};
int main() {
// Initialize.
Originator* org = new Originator("A");
std::cout << org->GetState().c_str() << std::endl;
// Save.
Caretaker* taker = new Caretaker();
taker->SetMemento(org->CreateMemento());
// Change.
org->SetState("B");
std::cout << org->GetState().c_str() << std::endl;
// Restore.
org->RestoreToMemento(taker->GetMemento());
std::cout << org->GetState().c_str() << std::endl;
return 0;
}