-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemento.cpp
92 lines (81 loc) · 1.71 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
84
85
86
87
88
89
90
91
92
//在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态
//https://zhuanlan.zhihu.com/p/636062329
#include <iostream>
#include <string>
#include <vector>
class Memento
{
public:
Memento(const std::string& state) : _state(state)
{
}
std::string GetState() const
{
return _state;
}
private:
std::string _state;
};
class Originator
{
public:
Originator() :_state("")
{
}
void SetState(const std::string& state)
{
_state = state;
}
Memento SaveStateToMemento()
{
return Memento(_state);
}
void RestoreStateFromMemento(const Memento& memento)
{
_state = memento.GetState();
}
std::string GetState() const
{
return _state;
}
private:
std::string _state;
};
class Caretaker
{
public:
void AddMemento(const Memento& memento)
{
_mementos.emplace_back(memento);
}
Memento GetMemento(int index) const
{
return _mementos[index];
}
private:
std::vector<Memento> _mementos;
};
//int main()
//{
// Originator originator;
// Caretaker caretaker;
//
// originator.SetState("State #1");
// originator.SetState("State #2");
// caretaker.AddMemento(originator.SaveStateToMemento());
//
// originator.SetState("State #3");
// caretaker.AddMemento(originator.SaveStateToMemento());
//
// originator.SetState("State #4");
//
// std::cout << "Current state: " << originator.GetState() << std::endl;
//
// originator.RestoreStateFromMemento(caretaker.GetMemento(0));
// std::cout << "First saved state: " << originator.GetState() << std::endl;
//
// originator.RestoreStateFromMemento(caretaker.GetMemento(1));
// std::cout << "Second saved state: " << originator.GetState() << std::endl;
//
// return 0;
//}