-
Notifications
You must be signed in to change notification settings - Fork 956
/
Copy pathMemento.cpp
147 lines (121 loc) · 2.41 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
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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
/*
* C++ Design Patterns: Memento
* Author: Jakub Vojvoda [github.com/JakubVojvoda]
* 2016
*
* Source code is licensed under MIT License
* (for more details see LICENSE)
*
*/
#include <iostream>
#include <vector>
/*
* Memento
* stores internal state of the Originator object and protects
* against access by objects other than the originator
*/
class Memento
{
private:
// accessible only to Originator
friend class Originator;
Memento( const int s ) : state( s ) {}
void setState( const int s )
{
state = s;
}
int getState()
{
return state;
}
// ...
private:
int state;
// ...
};
/*
* Originator
* creates a memento containing a snapshot of its current internal
* state and uses the memento to restore its internal state
*/
class Originator
{
public:
// implemented only for printing purpose
void setState( const int s )
{
std::cout << "Set state to " << s << "." << std::endl;
state = s;
}
// implemented only for printing purpose
int getState()
{
return state;
}
void setMemento( Memento* const m )
{
state = m->getState();
}
Memento *createMemento()
{
return new Memento( state );
}
private:
int state;
// ...
};
/*
* CareTaker
* is responsible for the memento's safe keeping
*/
class CareTaker
{
public:
CareTaker( Originator* const o ) : originator( o ) {}
~CareTaker()
{
for ( unsigned int i = 0; i < history.size(); i++ )
{
delete history.at( i );
}
history.clear();
}
void save()
{
std::cout << "Save state." << std::endl;
history.push_back( originator->createMemento() );
}
void undo()
{
if ( history.empty() )
{
std::cout << "Unable to undo state." << std::endl;
return;
}
Memento *m = history.back();
originator->setMemento( m );
std::cout << "Undo state." << std::endl;
history.pop_back();
delete m;
}
// ...
private:
Originator *originator;
std::vector<Memento*> history;
// ...
};
int main()
{
Originator *originator = new Originator();
CareTaker *caretaker = new CareTaker( originator );
originator->setState( 1 );
caretaker->save();
originator->setState( 2 );
caretaker->save();
originator->setState( 3 );
caretaker->undo();
std::cout << "Actual state is " << originator->getState() << "." << std::endl;
delete originator;
delete caretaker;
return 0;
}