来源:爱编程的大丙
定义:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个对象,这样以后需要的时候就可以将该对象恢复到原先保存的状态。
cpp
#include<iostream>
#include<map>
#include<vector>
#include<string>
using namespace std;
//历史备忘录
class History {
public:
History(string msg) :m_msg(msg) {}
string getHistory() {
return m_msg;
}
private:
string m_msg;
};
//鬼子
class JiaoPenJi {
public:
void setState(string msg) {
m_msg = msg;
}
string getState() {
return m_msg;
}
void beiDaddyDa() {
cout << "脚盆鸡被兔子狠狠地揍了又揍, 终于承认了它们之前不承认的这些罪行: " << endl;
}
//将鬼子罪行封装成一个历史对象,并通过返回值传出
History* saveHistory() {
return new History(m_msg);
}
//从一个历史对象·读出相关历史信息
void getStateFromHistory(History* history) {
m_msg = history->getHistory();
}
private:
string m_msg;
};
//记录者
class Recorder {
public:
void addHistory(int index, History* history) {
m_history.insert(make_pair(index, history));//添加历史信息,并保存
}
History* getHistory(int index) {//从备份信息中得到历史信息
if (m_history.find(index) != m_history.end()) {
return m_history[index];
}
return nullptr;
}
private:
map<int, History*>m_history;
};
int main() {
vector<string>msg{
"不承认偷了中国的中医!!!",
"不承认发动了侵华战争!!!",
"不承认南京大屠杀!!!!",
"不承认琉球群岛和钓鱼岛是中国的领土!!!",
"不承认731部队的细菌和人体试验!!!",
"不承认对我国妇女做出畜生行为!!!",
"不承认从中国掠夺的数以亿计的资源和数以万计的文物!!!",
"我干的龌龊事儿罄竹难书, 就是不承认......"
};
JiaoPenJi* jiaopen = new JiaoPenJi;
Recorder* recorder = new Recorder;
for (int i = 0; i < msg.size(); i++) {
jiaopen->setState(msg.at(i));
recorder->addHistory(i, jiaopen->saveHistory());
}
jiaopen->beiDaddyDa();
for (int i = 0; i < msg.size(); i++) {
jiaopen->getStateFromHistory(recorder->getHistory(i));
cout << "--" << jiaopen->getState() << endl;
}
return 0;
}