Memento模式在于不破坏封装,保存一个类的内部状态,这样可以利用该保存状态进行恢复操作。
 
    Memento的所有接口都申明为Private,并且将Originator作为其友元类,这样将ORI的状态保存在该模式类下,才可以达到封装效果。
 
 
#include<iostream>
#include<string>
using namespace std;
typedef string states;
 
class Memento;
class Orininator
{
public:
  Orininator(){m_st="";m_mt=0;};
  Orininator(const states& st){m_st=st;m_mt=0;};
  ~Orininator(){};
  Memento* CreateMemento();
  void SetMemento(Memento* men){};
  void RestoretoMen(Memento* mt);
  states GetState(){return m_st;};
  void SetState(const states& sdt){m_st=sdt;}
  void PrintState(){cout<this->m_st<<".."<<endl;}
private:
  states m_st;
  Memento* m_mt;
};
 
 
class Memento
{
private:
  friend class Orininator;//友元
  Memento(){};
  Memento(const states& st){m_st=st;};
  ~Memento(){};
  void SetState(const states& std){m_st=std;};
  states GetState(){return m_st;};
private:
  states m_st;
};
 
 
Memento* Orininator::CreateMemento()
{
 return new Memento(m_st);//合理的应用构造函数;
}
void Orininator::RestoretoMen(Memento* mt)
{
 this->m_st=mt->GetState();
}
 
 
void main()
{
 Orininator* Ori=new Orininator();
 Ori->SetState("old");
 Ori->PrintState();
 Memento* m=Ori->CreateMemento();
 Ori->SetState("new");
 Ori->PrintState();
 Ori->RestoretoMen(m);
 Ori->PrintState();
}


from :
http://blog.sina.com.cn/s/blog_48db23f601000750.html###
posted on 2009-10-01 15:30  AlexusLi  阅读(231)  评论(0编辑  收藏  举报