1.说明
请参阅第一篇文章
2.备忘录简介
备忘录:在不破坏封装的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后可以将该对象回复到保存时刻的状态
适用范围:适用于功能复杂,需要维护和记录属性的历史数据,需要保存的属性只是众多属性中的一小部分。使用备忘录模式可以将复杂的内部对象信息构建屏蔽起来
缺点:如果数据较多,消耗的内存资源相对也会比较多。
3.UML
4.代码
//数据保存对象
#ifndef __MEMENTO_H
#define __MEMENTO_H
#include <string>
class CMemento
{
public:
CMemento(std::string name, int sex, int combat)
{
m_name = name;
m_sex = sex;
m_combat = combat;
}
~CMemento(){}
public:
std::string m_name;
int m_sex;
int m_combat;
};
#endif
//保存数据的管理对象
#ifndef __CARETAKER_H
#define __CARETAKER_H
#include <iostream>
#include <map>
#include "Memento.h"
typedef std::map<int, CMemento*>TORIGINATORMAP;
class CCareTaker
{
public:
void scan_ori()
{
for (TORIGINATORMAP::iterator it=m_orimap.begin(); it!=m_orimap.end(); it++)
{
std::cout<<"no:"<<it->first<<" val--:"<<"name:"<<it->second->m_name.c_str()<<" sex:"<<
it->second->m_sex<<" combat:"<<it->second->m_combat<<std::endl;
}
}
void save_ori(int time, CMemento* val)
{
m_orimap.insert(std::make_pair(time, val));
}
CMemento* get_ori(int time)
{
CMemento* val = NULL;
TORIGINATORMAP::iterator it = m_orimap.find(time);
if (it != m_orimap.end())
val = it->second;
return val;
}
private:
TORIGINATORMAP m_orimap;
};
#endif
//数据源(数据生成对象)
#ifndef __ORIGINATOR_H
#define __ORIGINATOR_H
#include <iostream>
#include <string>
#include "Memento.h"
class COriginator
{
public:
COriginator(std::string name, int sex, int combat)
{
m_name = name;
m_sex = sex;
m_combat = combat;
}
~COriginator(){}
void setname(std::string name)
{
m_name = name;
}
std::string getname()
{
return m_name;
}
void setsex(int sex)
{
m_sex = sex;
}
int getsex()
{
return m_sex;
}
void setcombat(int combat)
{
m_combat = combat;
}
int getcombat()
{
return m_combat;
}
CMemento* save_ori()
{
return new CMemento(m_name, m_sex, m_combat);
}
void back_ori(CMemento* mem)
{
m_name = mem->m_name;
m_sex = mem->m_sex;
m_combat = mem->m_combat;
}
void print_ori()
{
std::cout<<"cur-state:"<<m_name.c_str()<<" "<<m_sex<<" "<<m_combat<<std::endl;
}
private:
std::string m_name;
int m_sex;
int m_combat;
};
#endif
//client 只和数据管理对象有交互
#include <iostream>
#include <unistd.h>
#include "Originator.h"
#include "CareTaker.h"
int main(void)
{
CCareTaker* taker = new CCareTaker();
COriginator* ori = new COriginator("zp", 1, 100);
taker->save_ori(1, ori->save_ori());
taker->save_ori(2, ori->save_ori());
ori->setname("xiaoli");
taker->save_ori(3, ori->save_ori());
ori->setsex(2);
taker->save_ori(4, ori->save_ori());
ori->print_ori();
taker->scan_ori();
ori->back_ori(taker->get_ori(4));
ori->print_ori();
return 0;
}