允许在不暴露对象实现细节的情况下,将对象恢复到之前的状态。

  • 快照对象应该是不可变对象,仅被初始化一次

快照发起者可以实现restore(Momento* m)方法,也可以由快照实现restore()方法。后者可以将快照对象与照看者对象(CareTaker)解耦。

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
class Editor {
private:
std::string text;
int curX, curY, selectionWidth;
public:
void setText(std::string t) {
text = t;
}
void setCursor(int x, int y) {
curX = x;
curY = y;
}
void setSelectionWdith(int w) {
selectionWidth = w;
}
Snapshot* createSnapshot() {
return new Snapshot(this, text, curX, curY, selectionWidth);
}
};

class Snapshot {
private:
Editor* editor;
std::string text;
int curX, curY, selectionWidth;
public:
Snapshot(Editor* e, std::string t, int x, int y, int w): editor(e), text(t), curX(x), curY(y), selectionWidth(w) {}
void restore() {
editor->setText(text);
editor->setCursor(curX, curY);
editor->setSelectionWidth(selectionWidth);
}
};

class Command {
private:
Snapshot* backup;
Editor* editor;
public:
Command(Editor* e): editor(e), backup(nullptr) {}
void makeBackup() {
backup = editor->createSnapshot();
}
void undo() {
if (backup) backup->restore();
}
virtual void execute() = 0;
};

class CopyCommand: public Command {
void execute() override {
// execute something
}
};