备忘录模式 我更想称它为快照模式,它的思想就是把对象的状态保存为快照,存储到其他地方,在需要的时候拿来加载上,就可以得到当时候存快照时的样子

比如我们游戏的存档点

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
92
93
94
95
96
97
98
#include <iostream>
#include <string>
#include <vector>

class ArchievePoint {
public:
ArchievePoint(std::string pos, int level, int money)
: m_pos(pos)
, m_level(level)
, m_money(money)
{}
std::string m_pos;
int m_level;
int m_money;
};

class Game {
public:
void show() {
std::cout << "当前在[" << m_pos << "] 等级:" << m_level << " 金币:" << m_money << std::endl;
}

void StageOne() {
m_pos = "光之谷";
m_level = 3;
m_money = 1000;
show();
}

void StageTwo() {
m_pos = "岩穴";
m_level = 10;
m_money = 3000;
show();
}
void StageThree() {
m_pos = "冰城";
m_level = 20;
m_money = 8000;
show();
}

ArchievePoint* Archive() {
return new ArchievePoint(m_pos, m_level, m_money);
}

void LoadArchieve(ArchievePoint* acv) {
m_pos = acv->m_pos;
m_level = acv->m_level;
m_money = acv->m_money;
show();
}

private:
std::string m_pos;
int m_level;
int m_money;
};

class ArchieveManager {
public:
void AddArchievePoint(ArchievePoint* acv) {
m_acvs.push_back(acv);
}

ArchievePoint* getArchievePoint(int index) {
if(index >= m_acvs.size()) {
return nullptr;
}
return m_acvs[index];
}

~ArchieveManager() {
for(auto item : m_acvs) {
delete item;
}
}
private:
std::vector<ArchievePoint*> m_acvs;
};

int main() {
ArchieveManager am;
Game game;

game.StageOne();
auto acv = game.Archive();
am.AddArchievePoint(acv);
game.StageTwo();
acv = game.Archive();
am.AddArchievePoint(acv);

std::cout << "==============================" << std::endl;
Game newgame;
newgame.LoadArchieve(am.getArchievePoint(1));
newgame.StageThree();
return 0;
}