5 Memento

Davids 2025-08-10 05:14:12
Categories: > > Tags:

备忘录模式:
对象状态在转换过程中,可能存在 回溯 到之前某个状态的需求。
实现对象状态的 保存与恢复,同时不破坏对象的封装性。
在 不破坏封装性 的前提下,捕获 一个对象的 内部状态,并在 对象之外 进行 保存 ,且支持恢复。
(已经不实用了,目前主流框架/语言,都有成熟的反射、序列化方案,可以更高效的实现备忘录模式)

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
class Memento {
private:
// 不一定通过字符串进行存储
std::string m_Content;
public:
Memento(const std::string&& content) : m_Content(content) {}
std::string GetMementoContent();
};

class Abstract {
private:
// some property
...
public:
Memento CreateMemento() {
// 序列化
...
return Memento(state);
}
void ApplyMemento(const Memento& memento) {
state = memento->GetMementoContent();
// 反序列化
...
}
};

class User {
void Do() {
Abstract abstract;
Memento memento = abstract.CreateMemento();
// do something
...
abstract.ApplyMemento(memento);
}
}