备忘录模式

备忘录模式, 在不破坏封装型的前提下, 捕获一个对象的内部状态, 并在该对象之外保存这个状态. 这样以后就可将该对象恢复到原先保存的状态.

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
class Originator {
private string state;
public string State {
get {
return state;
}
set {
state = value;
}
}

public Memento CreateMemento {
return (new Memento(state));
}

public void SetMemento(Memento memento) {
state = memento.State;
}

public void Show() {
// todo
}
}

class Memento {
private string state;

public Memento(string state) {
this.state = state;
}

public string State {
get {
return state;
}
}
}

class Caretaker {
private Memento memento;

public Memento Memento {
get {
return memento;
}
set {
memento = value;
}
}
}

public static void Main(string[] args) {
Originator originator = new Originator();
originator.State = "On";
originator.Show();

Caretaker caretaker = new Caretaker();
caretaker.Memento = originator.CreateMemento();

originator.State = "Off";
originator.Show();

originator.SetMemento(caretaker.Memento);
originator.Show();
}