-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmemento.cpp
More file actions
53 lines (41 loc) · 1017 Bytes
/
memento.cpp
File metadata and controls
53 lines (41 loc) · 1017 Bytes
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
#include <iostream>
#include <memory>
#include <string>
#include <vector>
using namespace std;
// Memento Token only stores the balance.
class Memento {
int balance;
public:
explicit Memento(int balance) : balance(balance) {}
// friend class so that private balance can be accessed.
friend class BankAccount;
};
class BankAccount {
int balance = 0;
public:
explicit BankAccount(const int balance) : balance(balance) {}
// Operation returns the token.
Memento deposit(int amount) {
balance += amount;
return Memento{balance};
}
// Apply memento token.
void restore(const Memento &m) { balance = m.balance; }
friend ostream &operator<<(ostream &os, const BankAccount &obj) {
return os << "balance: " << obj.balance;
}
};
int main() {
BankAccount ba{100};
auto m1 = ba.deposit(50); // 150
auto m2 = ba.deposit(25); // 175
cout << ba << "\n";
// undo to m1
ba.restore(m1);
cout << ba << "\n";
// redo
ba.restore(m2);
cout << ba << "\n";
return 0;
}