这个模式通常被翻译为备忘录模式,我并不是很欣赏这个翻译,不够浅显易懂啊~不用直译的话,叫备胎模式。
memento模式的逻辑很简单,或者说我没理解透,就是建一个类能够存贮state,以便在你需要的时候取出,当然事先有个备份,从代码上看,这个类是个隐藏类,只有通过originator才能使用。逻辑上没什么可以多说的,见图和代码吧。
图:
代码:
#ifndef _MEMENTO_H__
#define _MEMENTO_H__
#include <string>
using namespace std;
typedef string state;
class memento;
class originator
{
public:
originator();
originator(const state&);
~originator();
memento *create_memento();
void set_memento(memento *);
void restore_to_memento(memento *);
state get_state();
void set_state(const state &);
void print_state();
private:
state _sta;
memento *_p_mt;
};
class memento
{
private:
friend class originator;
memento(const state &);
~memento();
void set_state(const state &);
state get_state();
private:
state _sta;
};
//memento.cpp
#include "memento.h"
#include <iostream>
using namespace std;
originator::originator()
:_sta(""),_p_mt(0)
{
}
originator::originator(const state& st)
:_sta(st),_p_mt(0)
{
}
originator::~originator()
{
}
memento *originator::create_memento()
{
return new memento(_sta);
}
state originator::get_state()
{
return _sta;
}
void originator::set_state(const state &st)
{
_sta = st;
}
void originator::print_state()
{
cout<<"ORIGINATOR:"<<_sta<<"..."<<endl;
}
void originator::set_memento(memento *mem)
{
}
void originator::restore_to_memento(memento *mem)
{
_sta = mem->get_state();
}
//-----------------memento----------------
memento::memento(const state &st)
:_sta(st)
{
}
memento::~memento()
{
}
state memento::get_state()
{
return _sta;
}
void memento::set_state(const state &st)
{
_sta = st;
}
//main.cpp
#include "memento.h"
int main(int argc,char **argv)
{
originator *p_og = new originator();
p_og->set_state("old");
memento *p_mem = p_og->create_memento();
p_og->set_state("new");
p_og->print_state();
p_og->restore_to_memento(p_mem);
p_og->print_state();
return 0;
}
输出:
$ ./main.exe
ORIGINATOR:new...
ORIGINATOR:old...