我与C++设计模式(十六)——memento模式

这个模式通常被翻译为备忘录模式,我并不是很欣赏这个翻译,不够浅显易懂啊~不用直译的话,叫备胎模式。

memento模式的逻辑很简单,或者说我没理解透,就是建一个类能够存贮state,以便在你需要的时候取出,当然事先有个备份,从代码上看,这个类是个隐藏类,只有通过originator才能使用。逻辑上没什么可以多说的,见图和代码吧。

图:


代码:

#ifndef _MEMENTO_H__
#define _MEMENTO_H__

#include <string>
using namespace std;

typedef string state;
class memento;

class originator
{
        public:
                originator();
                originator(const state&);
                ~originator();

                memento *create_memento();
                void set_memento(memento *);
                void restore_to_memento(memento *);
                state get_state();
                void set_state(const state &);
                void print_state();

        private:
                state _sta;
                memento *_p_mt;
};

class memento
{
        private:
                friend class originator;

                memento(const state &);
                ~memento();
                void set_state(const state &);
                state get_state();

        private:
                state _sta;
};

//memento.cpp

#include "memento.h"
#include <iostream>
using namespace std;

originator::originator()
        :_sta(""),_p_mt(0)
{
}

originator::originator(const state& st)
        :_sta(st),_p_mt(0)
{
}

originator::~originator()
{
}

memento *originator::create_memento()
{
        return new memento(_sta);
}

state originator::get_state()
{
        return _sta;
}

void originator::set_state(const state &st)
{
        _sta = st;
}

void originator::print_state()
{
        cout<<"ORIGINATOR:"<<_sta<<"..."<<endl;
}

void originator::set_memento(memento *mem)
{
}

void originator::restore_to_memento(memento *mem)
{
        _sta = mem->get_state();
}

//-----------------memento----------------
memento::memento(const state &st)
        :_sta(st)
{
}

memento::~memento()
{
}

state memento::get_state()
{
        return _sta;
}

void memento::set_state(const state &st)
{
        _sta = st;
}

//main.cpp

#include "memento.h"

int main(int argc,char **argv)
{
        originator *p_og = new originator();
        p_og->set_state("old");
        memento *p_mem = p_og->create_memento();
        p_og->set_state("new");
        p_og->print_state();
        p_og->restore_to_memento(p_mem);
        p_og->print_state();

        return 0;
}
输出:
$ ./main.exe
ORIGINATOR:new...
ORIGINATOR:old...

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值