Memento模式

Memento模式

 
 
    在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原先保存的状态。
其实就是Undo操作,Memento模式可提供帮助。
    如果用接口来让其他对象直接得到这些状态,将会暴露对象的实现细节并破坏对象的封装性。
C++代码示例:

//memento.h

#ifndef MEMENTO_H
#define MEMENTO_H

#include <string>
#include <iostream>

using namespace std;
typedef string State;
class Memento;

class Originator{

public:
    typedef string State;
    Originator();
    Originator(const State& sta);
    ~Originator();
    Memento* createMemento();
    void setMemento(Memento* mem);
    void restoreToMemento(Memento* mem);
    State getState();
    void setState(const State& sta);
    void printState();
private:
    State m_sta;
    Memento* m_mem;

};

class Memento{

private:
    Memento();
    Memento(const State& sta);
    ~Memento();

    friend class Originator;
    typedef string State;

    void setState(const State& sta);
    State getState();
private:
    State m_sta;

};

#endif // MEMENTO_H

//memento.cpp

#include "memento.h"

Originator::Originator(){

    m_sta = "";
    m_mem = 0;
}

Originator::Originator(const State &sta){

    m_sta = sta;
    m_mem = 0;
}

Originator::~Originator(){

}

Memento* Originator::createMemento(){

    return new Memento(m_sta);
}

State Originator::getState(){

    return m_sta;
}

void Originator::setState(const State &sta){

    m_sta = sta;
}

void Originator::printState(){

    cout << "printState: " << this->m_sta << endl;
}

void Originator::setMemento(Memento *mem){

}

void Originator::restoreToMemento(Memento *mem){

    this->m_sta = mem->getState();
}

Memento::Memento(){

}

Memento::Memento(const State &sta){

    m_sta = sta;
}

State Memento::getState(){

    return m_sta;
}

void Memento::setState(const State &sta){

    m_sta = sta;
}

//main.cpp

#include "memento.h"

int main()
{
    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;
}

代码说明:

    Memento模式的关键就是friend class Originator(private),将Originator的状态保存在Memento类中,将Memento接口
设为private,从而达到封装。
    在Command模式中,Memento模式常被用来维护Undo的状态。




 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值