昨天正好实现了一个备忘录模式的示例
#ifndef _MEMENTO_H
#define _MEMENTO_H
#include
#include
using namespace std;
typedef string State;
class Memento
{
public:
~Memento();
private:
friend class Originator;
Memento(State s){
this->state = s;
}
void SetState(State s){
this->state = s;
}
State GetState(){
return state;
}
State state;
};
class Originator
{
public:
Originator(State s){
this->state = s;
}
void ChangeState(State s){
this->state = s;
}
Memento* CreateMemento(){
cout<
}
void RestoreMemento(Memento* mem){
cout<
}
void ShowState(string str){
cout<
private:
State state;
};
class CareTaker
{
private:
Memento* mem;
public:
CareTaker():mem(NULL){}
void SaveMemento(Memento* m){
cout<
}
Memento* GetMemento(){
return mem;
}
};
#endif //_MEMENTO_H
int main()
{
Originator *o = new Originator("start state.");
CareTaker *c = new CareTaker();
//show init state
o->ShowState("before change:");
//save state
c->SaveMemento(o->CreateMemento());
//change state
o->ChangeState("changed state.");
o->ShowState("after changed:");
//restore state
o->RestoreMemento(c->GetMemento());
o->ShowState("restored state:");
system("pause");
}
环境是vs2010,复制成两个文件,编译就能运行。解释的话,就不用了吧。。。
正如你说,备忘录模式。网上很多示例。。