设计模式 <行为型> | 备忘录模式

备忘录模式(Memento Pattern)

在不暴露对象实现细节的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,以便之后恢复对象为先前的状态。

结构图:

角色:

  1. 发起人(Originator):类可以生成自身状态的快照, 也可以在需要时通过快照恢复自身状态。
  2. 备忘录(Memento):存储发起人状态快照,在进行恢复时提供给发起人需要的状态。
  3. 管理者(Caretaker):备忘录管理者负责存储备忘录。

适用场景:

  1. 对象状态需要防丢失、撤销、恢复等场景下。

优点:

  1. 提供了一种可以恢复状态的机制,可以方便的回滚到某个版本。
  2. 不破坏对象封装情况的前提下创建对象状态快照。

缺点:

  1. 如果频繁创建备份或者备份的数据结构过大会消耗大量的内存。

代码(C#)

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
/// <summary>
/// 备忘录
/// </summary>
public class Memento
{
private string _state;

public Memento(string state)
{
_state = state;
}

public string GetState()
{
return _state;
}
}

/// <summary>
/// 发起类
/// </summary>
public class Originator
{
/// <summary>
/// 需要保存的状态
/// </summary>
private string _state;

public Originator(string state)
{
_state = state;
}

/// <summary>
/// 创建一个备忘录
/// </summary>
/// <returns></returns>
public Memento CreateMemento()
{
return (new Memento(_state));
}

/// <summary>
/// 获取状态
/// </summary>
/// <returns></returns>
public string GetState()
{
return _state;
}

/// <summary>
/// 设置状态
/// </summary>
/// <param name="memento"></param>
public void RestoreMemento(Memento memento)
{
_state = memento.GetState();
}
}

/// <summary>
/// 管理者,负责添加删除备忘录
/// </summary>
public class Caretaker
{
public List<Memento> Memento = new List<Memento>();

public void Add(Memento memento)
{
Memento.Add(memento);
}

public Memento Get(int index)
{
return Memento[index];
}
}

Originator a = new Originator("A");
Originator b = new Originator("B");

// 保存备忘录
Caretaker m = new Caretaker();
m.Memento.Add(a.CreateMemento());
m.Memento.Add(b.CreateMemento());

// 重新设置状态
b.RestoreMemento(m.Get(0));
Console.WriteLine(b.GetState());

最后

备忘录模式的实现很灵活,也没有很固定的实现方式,在不同的业务需求、不同编程语言下,代码实现可能都不大一样。只要满足在不违背封装原则的前提下,进行对象的备份和恢复就算是备忘录模式。


设计模式 <行为型> | 备忘录模式
http://example.com/posts/14647.html
作者
她微笑的脸y
发布于
2023年3月14日
许可协议