19.备忘录模式--Memento

 

Memento模式:
Memento模式在不破坏封装性的前提下捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象回复到原先保存的状态。因为Memento模式把要保存的细节封装在Memento中了,需要更改保存的细节也不用影响客户端

Memento模式比较适合用于功能比较复杂的,但需要维护或记录属性历史的类,或者需要保存的属性只是众多属性中的一小部分时,可以根据保存的Memento信息还原到前一状态。比如命令模式中,需要实现命令的撤销功能,那么命令模式可以使用Memento模式来存储可撤销操作的状态。在众多的游戏当中,都有存储进度的功能,实际上这就是Memento的应用,只不过游戏存盘时存在硬盘中而不是内存中。

Memento模式的典型结构图为:
 

Memento模式中封装的是需要保存的状态,当需要恢复的时候才取出来进行恢复.原理很简单,实现的时候需要注意一个地方:窄接口和宽接口.所谓的宽接口就是一般意义上的接口,把对外的接口作为public成员;而窄接口反之,把接口作为private成员,而把需要访问这些接口函数的类作为这个类的友元类,也就是说接口只暴露给了对这些接口感兴趣的类,而不是暴露在外部.下面的实现就是窄实现的方法来实现的.

下面是Memento模式的实现代码:

//Memento.h
#ifndef _MEMENTO_H_
#define _MEMENTO_H_
#include <string>
using namespace std;
class Memento;

class Originator
{
public:
    typedef string State;
    Originator();
    Originator(const State& sdt);
    ~Originator();
    Memento* CreateMemento();
    void SetMemento(Memento* men);
    void RestoreToMemento(Memento* mt);
    State GetState();
    void SetState(const State& sdt);
    void PrintState();
protected:
private:
    State _sdt;
    Memento* _mt;
};

class Memento
{
public:
protected:
private:
    //这是最关键的地方,将Originator为friend类,可以访问内部信息,但是其他类不能访问
    friend class Originator;
    typedef string State;
    Memento();
    Memento(const State& sdt);
    ~Memento();
    void SetState(const State& sdt);
    State GetState();
private:
    State _sdt;
};
#endif //~_MEMENTO_H_


//Memento.cpp
#include "Memento.h"
#include <iostream>
using namespace std;
typedef string State;
Originator::Originator()
{
    _sdt = "";
    _mt = 0;
}
Originator::Originator(const State& sdt)
{
    _sdt = sdt;
    _mt = 0;
}
Originator::~Originator()
{
}
Memento* Originator::CreateMemento()
{
    return new Memento(_sdt);
}
State Originator::GetState()
{
    return _sdt;
}
void Originator::SetState(const State& sdt)
{
    _sdt = sdt;
}
void Originator::PrintState()
{
    cout<<this->_sdt<<"....."<<endl;
}
void Originator::SetMemento(Memento* men)
{
}
void Originator::RestoreToMemento(Memento* mt)
{
    this->_sdt = mt->GetState();
}
//class Memento
Memento::Memento()
{
}
Memento::Memento(const State& sdt)
{
    _sdt = sdt;
}
State Memento::GetState()
{
    return _sdt;
}
void Memento::SetState(const State& sdt)
{
    _sdt = sdt;
}


//main.cpp
#include "Memento.h"
#include <iostream>
using namespace std;
int main(int argc,char* argv[])
{
    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;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值