C++设计模式之备忘录模式(Memento)

2025-05-27 0 76

当我们在实际应用中需要提供撤销机制,当一个对象可能需要再后续操作中恢复其内部状态时,就需要使用备忘录模式。其本质就是对象的序列化和反序列化的过程,支持回滚操作。

作用

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

类视图

C++设计模式之备忘录模式(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
typedef struct sysstate; //假设的一个空结构,用来代表系统状态

//还原点

class Memento

{

public:

Memento(sysstate &statein)

{

state = statein;

}

sysstate& getstate(){ return state}

private:

sysstate state;

};

//运行系统

class system

{

public:

void recovery(Memento* pMem)

{

if (pMem)

{

state = pMem->getstate();

}

}

Memento* backup()

{

return new Memento(state);

}

private:

sysstate state;

};

//还原控制器

class recoveryControl

{

public:

~recoveryControl()

{

map<long,Memento*>::iterator iter;

for ( iter = m_mementos.begin(); iter != m_mementos.end(); iter++)

{

delete iter.second;

}

}

long addRecoveryPoint(Memento* pMem)

{

long t = clock();

m_mementos.instert(pair<long,Memento*>(t, pMem));

return t;

}

Memento* GetRecoveryPoint(long time)

{

map<long,Memento*>::iterator iter;

iter = m_mementos.find(time);

if(iter != m_mementos.end())

return iter->second;

return NULL;

}

void DelRecoveryPoint(long time)

{

Memento* pMem = GetRecoveryPoint(time);

m_mementos.erase(time);

delete pMem;

}

private:

map<long,Memento*> m_mementos;

};

int main()

{

system Sys;

recoveryControl controler;

//备份系统并存入备份管理器中

long time1 = controler.addRecoveryPoint(Sys.backup());

long time2 = controler.addRecoveryPoint(Sys.backup());

//将系统恢复到time1状态

Sys.recovery(controler.GetRecoveryPoint(time1));

//将系统恢复到time2状态

Sys.recovery(controler.GetRecoveryPoint(time2));

}

应用场景

支持回滚操作的 地方,如游戏存档、事务回滚、程序的撤销和恢复操作等。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 C++设计模式之备忘录模式(Memento) https://www.kuaiidc.com/72736.html

相关文章

发表评论
暂无评论