码迷,mamicode.com
首页 > 编程语言 > 详细

设计模式C++实现十四:备忘录模式

时间:2015-05-13 14:57:23      阅读:152      评论:0      收藏:0      [点我收藏+]

标签: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;
}


设计模式C++实现十四:备忘录模式

标签:c++   面向对象   设计模式   备忘录模式   

原文地址:http://blog.csdn.net/shiwazone/article/details/45691043

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!