请问如何用C++使用备忘录模式和命令模式实现undo redo

2025-05-13 22:00:17
推荐回答(2个)
回答(1):

昨天正好实现了一个备忘录模式的示例

#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<return new Memento(this->state);
}
void RestoreMemento(Memento* mem){
cout<this->state = mem->GetState();
}
void ShowState(string str){
cout<}
private:
State state;
};

class CareTaker
{
private:
Memento* mem;
public:
CareTaker():mem(NULL){}
void SaveMemento(Memento* m){
cout<mem = m;
}
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,复制成两个文件,编译就能运行。解释的话,就不用了吧。。。

回答(2):

正如你说,备忘录模式。网上很多示例。。