[设计模式]备忘录 (二)

2014-11-24 01:02:44 · 作者: · 浏览: 10
*************/



/**
* @file test_memento.cpp
* @author itegel
* @date 2013/06/08 11:29:08
* @brief
*
**/

#include
#include
#include
using namespace std;

class State{
public:
int version;
string content;
};

class Memento{
public:
private:
friend class NoteBook;
Memento(State state) : _state(state){}
~Memento(){}

State * GetState(){
return &_state;
}
void SetState(State state){
_state = state;
}
State _state;
};

//originator
class NoteBook{
public:
NoteBook(int version, string content){
_state.version = version;
_state.content = content;
}

NoteBook(State & state):_state(state){

}

void SetMemento(Memento * mem){
_state = mem->_state;
}

Memento * GetMemento(){
return new Memento(_state);
}

void SetState(int version, string content){
_state.version = version;
_state.content = content;
}

int GetVersion(){
return _state.version;
}

void PrintState(){
cout<<"Note:\n\tversion:\t"<<_state.version< }

private:
State _state;
};


class CareTaker{
public:
CareTaker(){}
void Save(int id, Memento * mem){
_memento_map[id] = mem;
}
Memento * GetMemento(int id){
return _memento_map[id];
}
private:
map _memento_map;
};

int main(){
NoteBook my_note(0, "");
CareTaker care_taker;

my_note.PrintState();
cout<<"Save State 0!"< care_taker.Save(my_note.GetVersion(), my_note.GetMemento());

cout< my_note.SetState(1, "Hello world!");
my_note.PrintState();
care_taker.Save(my_note.GetVersion(), my_note.GetMemento());

cout< my_note.SetState(2, "Hello World! It is the 2nd version!");
my_note.PrintState();
care_taker.Save(my_note.GetVersion(), my_note.GetMemento());

cout< my_note.SetState(3, "Hello Itegel! It is the 3rd version!");
my_note.PrintState();
care_taker.Save(my_note.GetVersion(), my_note.GetMemento());


cout< Memento * mem = care_taker.GetMemento(2);
my_note.SetMemento(mem);
my_note.PrintState();

cout< mem = care_taker.GetMemento(0);
my_note.SetMemento(mem);
my_note.PrintState();

return 0;
}


执行结果:


[plain]
Note:
version: 0
content:
Save State 0!

Edit for 1st time!
Note:
version: 1
content: Hello world!

Edit for 2nd time!
Note:
version: 2
content: Hello World! It is the 2nd version!

Edit for 3rd time!
Note:
version: 3
content: Hello Itegel! It is the 3rd version!

Restore 2nd version:
Note:
version: 2
content: Hello World! It is the 2nd version!

Restore 0 version:
Note:
version: 0
content:

Note:
version: 0
content:
Save State 0!

Edit for 1st time!
Note:
version: 1
content: Hello world!

Edit for 2nd time!
Note:
version: 2
content: Hello World! It is the 2nd version!

Edit for 3rd time!
Note:
version: 3
content: Hello Itegel! It is the 3rd version!

Restore 2nd version:
Note:
version: 2
content: Hello World! It is the 2nd version!

Restore 0 version:
Note:
version: 0
content:

备忘录模式使用场景应该比较固定,但是其实现可以很灵活。主要思想就是将自己的状态托管给一个