现在的位置: 首页 > 综合 > 正文

设计模式——备忘录模式_Memento Pattern

2013年11月24日 ⁄ 综合 ⁄ 共 1733字 ⁄ 字号 评论关闭

备忘录模式:

Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later.(在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。


C++实现:

#ifndef __MEMENTO_H__
#define __MEMENTO_H__

#include <iostream>
#include <string>
using namespace std;

class Originator;

class Memento {
public:
	typedef string State;
	friend class Originator;
	Memento(State& state) : _state(state) { }
	State GetState() { return _state; }
	void SetState(const State& state) { _state = state; }
private:
	State _state;
};

class Originator {
public:
	typedef string State;
	Originator(State& state) : _state(state) { }
	State GetState() { return _state; }
	void SetState(const State& state) { _state = state; }
	Memento* CreateMemento() { return new Memento(this->_state); }
	void RestoreMemento(Memento* meme) { cout << "还原状态:"; this->_state = meme->GetState(); }
	void ShowState() { cout <<"ShowState() --> " << _state << endl; }
private:
	State _state;
	Memento* _pMemento;
};

class CareTaker {
public:
	CareTaker(Memento* pMemento):_pMemento(pMemento) { }
	Memento* GetMemeto() { return _pMemento; }
	void SetMemeto(Memento* pMemento) { _pMemento = pMemento; }
private:
	Memento* _pMemento;
};

#endif //__MEMENTO_H__

#include "Memento.h"


int main()
{
	Originator* pOriginator = new Originator(string("old"));
	pOriginator->ShowState();

	Memento* pMem = pOriginator->CreateMemento();
	CareTaker* pTaker = new CareTaker(pMem);
	pOriginator->SetState("new");
	pOriginator->ShowState();

	pOriginator->RestoreMemento(pTaker->GetMemeto());
	pOriginator->ShowState();

	delete pTaker;
	delete pMem;
	delete pOriginator;

	return 0;
}

当前模式有Originator,Memento,Caretaker三种角色,可以精简利用原型模式Clone把3个角色全并到Originator上去。即Clone方式的备忘录(仅应用在小规模或场景单一的情况下,若要与其他对象产生严重耦合关系考虑换用多状态备忘录模式,关联一张Hashmap)

多备份的备忘录模式,即备份的备份。关联2张Hashmap

更强的封装性,声明一个空接口IMemento,类中类Memeto实现其接口,并在Originator类中private声明。那么对于备忘也只能由发起人Originator独自享用了。外部可以通过关联访问IMemento的接口。

抱歉!评论已关闭.