天天看點

設計模式C++實作十四:備忘錄模式

備忘錄模式(Memento):在不破壞封裝性的前提下,捕獲一個對象的内部狀态,并在該對象之外儲存這個狀态,這樣以後就可以将該對象恢複到之前儲存的狀态。

備忘錄模式比較适用于功能較複雜的,但需要維護和記錄屬性曆史的類,或者需要儲存的屬性隻是衆多屬性中的一小部分。如果某個系統中使用指令模式時,需要實作指令的撤銷功能,那麼備忘錄模式可以存儲可撤銷操作的狀态。

#ifndef MEMENTO_H
#define MEMENTO_H
#include<iostream>
#include<string>
using namespace std;
class RoleStateMemento;
class GameRole
{
	friend class RoleStateMemento;
	int vit;
	int atk;
	int dfs;
public:
	GameRole():vit(100),atk(100),dfs(100){}
	//void Initial();
	void Fight1();
	void Fight2();
	void RecoveryState(RoleStateMemento m);
	RoleStateMemento SaveState();
	void StateDisplay();
};

class RoleStateMemento
{
	friend class GameRole;
	int vit;
	int atk;
	int dfs;
public:
	RoleStateMemento(){}
	RoleStateMemento(GameRole role);

};

class RoleStateDirector
{
	RoleStateMemento memento;
public:
	RoleStateDirector(GameRole role);
	RoleStateDirector(RoleStateMemento role);
	RoleStateMemento ReturnMemento();
};

void GameRole::Fight1()
{
	vit = 80;
	atk = 60;
	dfs = 50;
}
void GameRole::Fight2()
{
	vit = 30;
	atk = 40;
	dfs = 40;
}
void GameRole::RecoveryState(RoleStateMemento m)
{
	vit = m.vit;
	atk = m.atk;
	dfs = m.dfs;
}
RoleStateMemento GameRole::SaveState()
{
	return RoleStateMemento(*this);
}
void GameRole::StateDisplay()
{
	cout << "Vitality: " << vit << endl;
	cout << "Attack: " << atk << endl;
	cout << "Defense: " << dfs << endl;
}

RoleStateMemento::RoleStateMemento(GameRole role)
{
	vit = role.vit;
	atk = role.atk;
	dfs = role.dfs;
}
RoleStateDirector::RoleStateDirector(GameRole role):memento(role){}
RoleStateDirector::RoleStateDirector(RoleStateMemento role) : memento(role){}
RoleStateMemento RoleStateDirector::ReturnMemento()
{
	return memento;
}
#endif
           
#include"Memento.h"
int main()
{
	GameRole Xie;
	Xie.StateDisplay();

	Xie.Fight1();
	Xie.StateDisplay();

	RoleStateDirector Dir(Xie.SaveState());

	Xie.Fight2();
	Xie.StateDisplay();

	Xie.RecoveryState(Dir.ReturnMemento());
	Xie.StateDisplay();
	return 0;
}
           

繼續閱讀