背景
在软件构建过程中,某些对象的状态在转换过程中,可能由于某种需要,要求程序能够回溯到对象之前处于某个点的状态。如果使用一些公有接口让其他对象得到对象的状态,便会暴露对象的实现细节。
关键
在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原先保存的状态。
核心
备忘录模式的核心是:信息隐藏,即原发器需要向外接隐藏信息,保持其封装性。但同时有需要将状态保持到外界。
特点
备忘录(Memento)存储原发器对象内部的状态,在需要时恢复原发器状态。
代码说明
Memento 模式的关键就是
friend class Originator;
Memento 的接口都声明为 private,而将 Originator 声明为 Memento 的友元类。我们将 Originator 的状态保存在Memento 类中,而将 Memento 接口 private 起来,也就达到了封装的功效。在 Originator 类中通RestoreMemento接口让用户恢复状态。
在测试程序中Originator 的状态由 old 变为 new 最后又变为 old。
代码
//Memento.h
#pragma once
#include<string>
using namespace std;
class Memento;
class Originator {
public:
~Originator();
Originator();//默认构造
Originator(const string& str);//初始化
void SetState(const string& str);//设置状态
string GetState();//获取状态
void printState();//打印状态信息
//Memento
Memento* CreateMemento();//创建备忘录
void SetMemento(Memento* memento);//设置备忘录状态
void RestoreMemento(Memento* memento);//恢复备忘录状态
private:
Memento* memento;
string str;
};
class Memento {
private:
friend class Originator;
~Memento();
Memento();
Memento(const string& str);
void SetState(const string& str);//设置状态
string GetState();//获取状态
private:
string str;
};
//Memento.cpp
#include"Memento.h"
#include<iostream>
using namespace std;
//Originator
Originator::~Originator() {
}
Originator::Originator() {
this->str = "\0";
this->memento = 0;
}
Originator::Originator(const string& str) {
this->str = str;
this->memento = 0;
}
void Originator::SetState(const string& str) {
this->str = str;
}
string Originator::GetState() {
return this->str;
}
void Originator::printState() {
cout << this->str << endl;
}
//创建备忘录用来记录当前状态
Memento* Originator::CreateMemento() {
return new Memento(str);
}
void Originator::SetMemento(Memento* memento) {
}
//将备忘录里面存储的状态恢复
void Originator::RestoreMemento(Memento* memento) {
this->str = memento->GetState();
}
//Memento
Memento::~Memento() {
}
Memento::Memento() {
}
Memento::Memento(const string& str) {
this->str = str;
}
void Memento::SetState(const string& str) {
this->str = str;
}
string Memento::GetState() {
return this->str;
}
//Main.cpp
#include"Memento.h"
#include<iostream>
using namespace std;
int main() {
Originator* originator = new Originator();
originator->SetState("old");
originator->printState();//old
Memento* memento = originator->CreateMemento();//创建备忘录
originator->SetState("new");
originator->printState();//new
originator->RestoreMemento(memento);//恢复状态
originator->printState();//new
delete originator;
return 0;
}
运行结果