备忘录【设计模式】

知识点

备忘录(memento)、token

知识内容

在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。

示例

#include<iostream>

using namespace std;

class Memento
{
  private:
   int state;
  public:
   Memento(int myState):state(myState){}
   int GetState()
   {
     return this -> state;
   }
   void SetState(int myState)
   {
     this -> state = myState;
   }
};

class Originator
{
  private:
    int state;
  public:
    Memento* CreateMemento()
    {
      cout << "save state..." << endl;
      Memento* memento = new Memento(state);
     return memento; 
    }
    void SetMemento(Memento* m)
    {
      cout << "restore state..." << endl;
      this -> state = m -> GetState();  
    }
    int GetState()
    {
      return this -> state;
    }
    void SetState(int myState)
    {
      this -> state = myState;
    }
};
int main()
{
  Originator* originator = new Originator();
  cout << "current state:" << originator -> GetState() << endl;
  Memento* memento = originator -> CreateMemento();
  int state = 100;
  originator -> SetState(100);
  cout << "current state:" << originator -> GetState() << endl;
  originator -> SetMemento(memento);
  cout << "current state:" << originator -> GetState() << endl;
  return 0;
}

链接

https://github.com/xierensong/learngit/blob/master/DPattern/17/1.cpp

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值