0%

设计模式-备忘录模式

在不破坏封装性的前提下, 捕获一个对象的内部状态, 并在该对象之外保存这个状态

备忘录模式

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
//发起人Originator
class Originator
{
private string state;
public string State{get;set;}
//创建备忘录保存
public Memento CreateMemento()
{
return new Memento(state);
}
//恢复数据
public void SetMemento(Memento memento)
{
state = memento.State;
}
public void Show()
{
Console.WriteLine("State = " + state);
}
}
//备忘录Memento
//封装保存细节
class Memento
{
private string state;
public string State{get;}
public Memento(string state)
{
this.state = state;
}
}
//管理者Caretaker
class Caretaker
{
private Memento memento;
public Memento Memento{get; set;}
}
//Client
Originator o = new Originator();
o.State = "On";
o.Show();

Caretaker c = new Caretaker();
c.Memento = o.CreateMemento();

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

o.SetMemento(c.Memento);
o.Show();