【C++设计模式】备忘录模式

#ifndef __MEMENTO_H__
#define __MEMENTO_H__

//【说明】
// 在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态。

//【定义】
// 备忘录模式:事先将某个时间点的实例的状态保存下来,之后在有必要时,再将实例恢复至当时的状态。

//【角色】
// Originator(发起人):负责创建一个备忘录Memento,用以记录当前时刻自身的内部状态,并可使用备忘录恢复内部状态。
// Memento(备忘录):负责存储Originator对象的内部状态,并可以防止Originator以外的其他对象访问备忘录。
// Caretaker(管理者): 负责备忘录Memento,不能对Memento的内容进行访问或者操作。

//【意义】
// 备忘录模式适合功能比较复杂的,但需要维护或记录属性历史的功能。

//【示例】
// 比如我们玩的游戏的存档功能,就可以通过备忘录实现。

// 备忘录角色,用于保存某个实例的重要状态,如玩家的生命值
class Memento
{
public:
	Memento(int life) : m_life(life){ }

	~Memento(){ }

public:
	int GetLife();

private:
	int m_life;
};

// 敌人
class Enemy
{
public:
	Enemy(int life) : m_life(life){ }

	~Enemy(){ }

public:
	int GetLife();

private:
	int m_life;
};

// 玩家(发起人)
class Gamer
{
public:
	Gamer(int life) : m_life(life){ }

	~Gamer(){ }

public:
	//创建备忘录
	Memento * CreateMemento();

	//恢复到备忘状态
	void RestoreMemento(Memento * memento);

	//同敌人战斗,扣除生命
	int FightWith(Enemy * army);

	int GetLife();

private:
	int m_life;
};

void TestMemento();


#endif

#include <stdio.h>
#include "Memento.h"

int Memento::GetLife()
{
	return m_life;
}

int Enemy::GetLife()
{
	return m_life;
}

Memento * Gamer::CreateMemento()
{
	return new Memento(m_life);
}

void Gamer::RestoreMemento(Memento * memento)
{
	m_life  = memento->GetLife();
}

int Gamer::FightWith(Enemy * army)
{
	m_life -= army->GetLife();

	if (m_life > 0)
	{		
		printf("Win \n");
		return 0;
	}
	else
	{
		printf("Lose \n");
		return -1;
	}
}

int Gamer::GetLife()
{
	return m_life;
}

void TestMemento()
{
	Gamer * gamer = new Gamer(100);
	Memento * memento = gamer->CreateMemento();

	for (int i=0; i<100; i++)
	{
		Enemy enemy(i);

		//同敌人战斗,获胜则保存状态到备忘录,失败则回退到上次备忘状态
		if (gamer->FightWith(&enemy) == 0)
		{
			delete memento;
			memento = gamer->CreateMemento();
		}
		else
		{
			gamer->RestoreMemento(memento);
			break;
		}
	}

	printf("gamer life is %d. \n", gamer->GetLife());

	delete memento;
	delete gamer;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值