设计模式备忘录模式

备忘录模式Memento):

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


Originator发起人):负责创建一个备忘录Memento,用以记录当前时刻它的内部状态,并且使用备忘录恢复内部状态。Originator可根据需要决定Memento存储Originator的哪些内部状态。

Memento备忘录):负责存储Originator对象的内部状态,并可防止Originator以外的其他对象访问备忘Memento。备忘录有两个接口,Caretaker只能看到备忘录的窄接口,它只能讲备忘录传递给其他对象。Originator能够看到一个宽接口,允许它访问返回到先前状态所需要的所有数据。
Caretaker管理者):负责保存好备忘录Memento,不能对备忘录的内容进行操作或检查。
备忘录模式代码:
#pragma once
#include <string>
#include <iostream>
using namespace std;

//备忘录(Memento)
class Cmemento
{
public:
	string m_strState;
public:
	Cmemento(string strState)
	{
		m_strState = strState;
	}
};

//发起人(Originator)类
class COriginator
{
public:
	string m_strState;
public:
	Cmemento * CreateMemento()
	{
		return new Cmemento(m_strState);
	}
	void SetMemento(Cmemento * pMemento)
	{
		m_strState = pMemento->m_strState;
	}
	void Show()
	{
		cout<<"State="<<m_strState<<endl;
	}
};

//管理者(Creataker)类
class CCaretaker
{
public:
	Cmemento *m_pMemento;
};
客户端使用代码:
#include "stdafx.h"
#include "MementoMode.h"
#include <windows.h>
using namespace std;

int main()
{
	COriginator *pO = new  COriginator();
	pO->m_strState = "On";
	pO->Show();

	CCaretaker *pC = new CCaretaker();
	pC->m_pMemento = pO->CreateMemento();

	pO->m_strState = "Off";
	pO->Show();

	pO->SetMemento(pC->m_pMemento);
	pO->Show();

	delete pO;
	delete pC->m_pMemento;
	delete pC;

	return 0;
}
运行结果:


OK上面就是备忘录模式,其实可以想成是某个软件的临时快照等等,但是上面的很多地方用了public,本身应该考虑set,get的,为了方便就直接public了,但是应该要清楚这么写对封装一点没有好处,而且写的时候也会很难受。今天又太晚了,我就不改了就上面那样吧,大家理解备忘录模式的思想就好。
原文地址:https://www.cnblogs.com/csnd/p/12062336.html