【C++】大话设计模式C++实现,备忘录模式Memento

《大话数据结构》一书中实例代码使用C#,这里用C++实现一遍

 

//备忘录模式
//窄接口和宽接口


#pragma once
#include 
using std::cout;
using std::endl;

//角色状态备忘录
class RoleStateMemento {
private:
	int vit; //生命力
	int atk; //攻击力
	int def; //防御力
public:
	RoleStateMemento(int v = 100, int a = 100, int d = 100)
		:vit(v), atk(a), def(d)
	{}

	int & accessVitality() {
		return vit;
	}
	int & accessAttack() {
		return atk;
	}
	int & accessDefense() {
		return def;
	}

};

//角色状态管理者(拥有备忘录的窄接口:整体传递备忘录)
//把备忘录放进属性里保存或是取出
class RoleStateCaretaker {
private:
	RoleStateMemento *memento = nullptr;
public:
	~RoleStateCaretaker() {
		delete memento;
	}
	
	
	RoleStateMemento *getMemento() {
		return memento;
	}
	void setMemento(RoleStateMemento * m) {
		memento = m;
	}
};



//游戏角色类(拥有备忘录的宽接口:备忘录细节)
class Role {
private:
	int vit = 100; //生命力
	int atk = 100; //攻击力
	int def = 100; //防御力

public:
	RoleStateMemento * saveState() { //导出保存状态
		return new RoleStateMemento(vit, atk, def);
	}
	void recoveryState(RoleStateMemento * r) { //导入恢复状态
		vit = r->accessVitality();
		atk = r->accessAttack();
		def = r->accessDefense();
	}
	void showState() {
		cout << "生命力:" << vit << endl;
		cout << "攻击力:" << atk << endl;
		cout << "防御力:" << def << endl;
	}
	void fight() {
		vit = 0; 
		atk = 0;
		def = 0; 
	}

};




	//备忘录模式
	cout << endl << "备忘录模式" << endl;
	Role saber;
	//保存状态
	RoleStateCaretaker manager;
	manager.setMemento(saber.saveState());
	saber.showState();

	saber.fight();
	saber.showState();

	saber.recoveryState(manager.getMemento());
	saber.showState();

 

你可能感兴趣的:(【C++】大话设计模式C++实现,备忘录模式Memento)