文章目录
  1. 备忘录模式

备忘录模式

  • 在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。
    Memento
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
public class IterOriginator {
private final Node root;
private Node cursor = null;
private Boolean isDone = false;
private Stack<Node> stack;
private Memento<Node> memento;
public IterOriginator(Node root) {
this.root = root;
stack = new Stack<>();
cursor = root;
stack.push(cursor);
}
public Node next() {
memento = createMemento();
if (stack.isEmpty()) {
isDone = true;
return null;
}
Node top = stack.pop();
cursor = top.right;
if (cursor != null) {
stack.push(cursor);
}
cursor = top.left;
if (cursor != null) {
stack.push(cursor);
}
return top;
}
public void undo() {
setMemento(memento);
}
public Memento<Node> createMemento() {
Memento<Node> memento = new Memento<>();
Stack newStack=(Stack)stack.clone();
memento.status = newStack;
return memento;
}
public void setMemento(Memento<Node> memento) {
this.stack = memento.status;
}
}
public class Memento<T> {
public Stack<T> status;
}
public class Node {
public Node left;
public Node right;
public String name;
public Node(Node left, Node right, String name) {
this.left = left;
this.right = right;
this.name = name;
}
public Node(String name) {
this.name = name;
}
public IterOriginator createFrontIndexIterator() {
return new IterOriginator(this);
}
}
public class App {
public static void main(String[] args) {
Node one = new Node(
new Node(new Node(new Node("8"),null,"3"), new Node(new Node("6"), new Node("7"), "4"), "2"),
new Node(new Node("9"),null,"5"), "1");
IterOriginator iterOriginator=one.createFrontIndexIterator();
Memento first=iterOriginator.createMemento();
System.out.println(iterOriginator.next().name);
System.out.println(iterOriginator.next().name);
iterOriginator.setMemento(first);
System.out.println(iterOriginator.next().name);
System.out.println(iterOriginator.next().name);
}
}
文章目录
  1. 备忘录模式