Memento模式
将状态保存,很简单,看看就能懂
Memento.h
#ifndef _MEMENTO_H
#define _MEMENTO_H
#include <iostream>
#include <string>
using namespace std;
class Originator;
class Memento
{
public:
protected:
private:
friend class Originator;
Memento() {
}
Memento(const string& sdt) {
_sdt = sdt;
}
~Memento() {
}
void SetState(const string& sdt) {
_sdt = sdt;
}
string GetState() {
return _sdt;
}
private:
string _sdt;
};
class Originator
{
public:
Originator() {
_sdt = "";
_mt = NULL;
}
Originator(const string& sdt) {
_sdt = sdt;
_mt = NULL;
}
~Originator() {
}
Memento* CreateMemento() {
return new Memento(_sdt);
}
string GetState() {
return _sdt;
}
void SetState(const string& sdt) {
_sdt = sdt;
}
void PrintState() {
cout << _sdt << endl;
}
void SetMemento(Memento* men) {
_mt = men;
}
void RestoreToMemento(Memento* mt) {
_sdt = mt->GetState();
}
private:
string _sdt;
Memento* _mt;
};
#endif // _MEMENTO_H
Memento.cpp
#include "Memento.h"
int main()
{
Originator* o = new Originator;
o->SetState("old");
o->PrintState();
Memento* m = o->CreateMemento();
o->SetState("new");
o->PrintState();
o->RestoreToMemento(m);
o->PrintState();
return 0;
}
编译:make Memento