C++设计模式17:Memento模式

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###

转载于:https://www.cnblogs.com/alexusli/archive/2009/10/01/1577230.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值