-
Notifications
You must be signed in to change notification settings - Fork 1
/
Memento.java
63 lines (51 loc) · 1.17 KB
/
Memento.java
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
// Memento pattern
package behavioral.memento;
// bank account token here
class Memento
{
private int balance;
public int getBalance() {
return balance;
}
public Memento(int balance) {
this.balance = balance;
}
}
class BankAccount
{
private int balance;
public BankAccount(int balance) {
this.balance = balance;
}
// instead of operations be void, they return a memento
public Memento deposit(int amount)
{
balance += amount;
return new Memento(balance);
}
public void restore(Memento m)
{
balance = m.getBalance();
}
@Override
public String toString() {
return "BankAccount{" +
"balance=" + balance +
'}';
}
}
class MementoDemo
{
public static void main(String[] args) {
BankAccount ba = new BankAccount(100);
Memento memento1 = ba.deposit(50); // 150
Memento memento2 = ba.deposit(25); // 175
System.out.println(ba);
// restore to m1
ba.restore(memento1);
System.out.println(ba);
// restore to m2
ba.restore(memento2);
System.out.println(ba);
}
}