-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMemento.java
More file actions
63 lines (47 loc) · 1.39 KB
/
Memento.java
File metadata and controls
63 lines (47 loc) · 1.39 KB
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
import java.util.ArrayList;
import java.util.List;
class Token {
public int value = 0;
public Token(int value) {
this.value = value;
}
public String toString() {
return ""+value;
}
}
class Memento {
public List<Token> tokens = new ArrayList<>();
public Memento(List<Token> tokens) {
tokens.stream().map(t -> new Token(t.value)).forEach(this.tokens::add);
}
}
class TokenMachine {
public List<Token> tokens = new ArrayList<>();
public Memento addToken(int value) {
return addToken(new Token(value));
}
public Memento addToken(Token token) {
tokens.add(token);
return new Memento(tokens);
}
public void revert(Memento m) {
tokens = m.tokens;
}
public String toString() {
return tokens.toString() + System.lineSeparator();
}
}
class DemoMemento {
public static void main(String[] args) {
TokenMachine tm = new TokenMachine();
tm.addToken(10);
Token t1 = new Token(20);
tm.addToken(t1);
Memento m1 = tm.addToken(t1);
System.out.print("State 1 " + tm.toString());
t1.value = 50;
System.out.print("State 2 " + tm.toString());
tm.revert(m1);
System.out.print("State 1? " + tm.toString());
}
}