十四、备忘录模式

备忘录(Memento)在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

//Originator.h
/*
Originator(发起人)负责创建一个备忘录Memento,用以记录当前时刻他的内部状态
并可以使用备忘录恢复内部状态。
*/
#ifndef _ORTIGINATOR_H_
#define _ORTIGINATOR_H_
#include <string>
#include <iostream>
using namespace std;
class Memento;
class Originator
{
private:
	string _state;
public:
	Originator()
	{
		_state="";
	}
	void SetState(const string& st)
	{
		_state = st;
	}
	string GetState()
	{
		return _state;
	}
	void SetMomento(Memento* mot)
	{
		_state = mot->GetState();
	}
	Memento* CreateMemonto()
	{
		return new Memento(_state);
	}
	void Show()
	{
		cout<<"State: "<<_state<<endl;
	}
};
#endif

//Memento.h
/*
负责存储originator对象的内部状态,并可防止Originator以外的其他对象访问备忘录。
备忘录有两个接口,Caretaker只能看到备忘录的窄接口,他只能将备忘录传递给其他对象,
Originator能够看到一个宽接口,允许它访问返回到先前的状态所需的所有数据。
*/
#ifndef _MEMENTO_H_
#define _MEMENTO_H_
#include <string>
using namespace std;
class Memento
{
public:
	Memento(string st)
	{
		_state = st;
	}
	string GetState()
	{
		return _state;
	}
private:
	string _state;
};
#endif

//CareTaker.h
//CareTaker负责保存备忘录,不对其进行修改
#ifndef _CARETAKER_H_
#define _CARETAKER_H_
class Memento;
class CareTaker
{
private:
	Memento* _mo;
public:
	void SetMemonto(Memento* mo)
	{
		_mo = mo;
	}
	Memento* GetMomento()
	{
		return _mo;
	}
};
#endif

#include "Memonto.h"
#include "Originator.h"
#include "CareTaker.h"

int main()
{
	Originator* or =new Originator();
	or->SetState("On");
	or->Show();

	CareTaker* ct = new CareTaker();
	ct->SetMemonto(or->CreateMemonto());

	or->SetState("Off");
	or->Show();

	or->SetMomento(ct->GetMomento());
	or->Show();
	return 0;
}

//main.cpp
#include "Memonto.h"
#include "Originator.h"
#include "CareTaker.h"

int main()
{
	Originator* or =new Originator();
	or->SetState("On");
	or->Show();

	CareTaker* ct = new CareTaker();
	ct->SetMemonto(or->CreateMemonto());

	or->SetState("Off");
	or->Show();

	or->SetMomento(ct->GetMomento());
	or->Show();
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值