大话设计模式备忘录模式c++实现

备忘录模式

其他二十三种设计模式

#include<iostream>
using namespace std;

//备忘录模式
//角色状态备忘录类
class RoleStateMemento {
    
    
public:
	RoleStateMemento(int _vit,int _atk,int _def) {
    
    
		this->vit = _vit;
		this->atk = _atk;
		this->def = _def;
	}
	void SetVitality(int _vit) {
    
    
		this->vit = _vit;
	}
	int GetVitality() {
    
    
		return vit;
	}
	void SetAttack(int _atk) {
    
    
		this->atk = _atk;
	}
	int GetAttack() {
    
    
		return atk;
	}
	void SetDefense(int _def) {
    
    
		this->def = _def;
	}
	int GetDefense() {
    
    
		return def;
	}

private:
	int vit;
	int atk;
	int def;
};

//角色类
class GameRole {
    
    
public:
	int GetVitality(int _vit) {
    
    
		this->vit = _vit;
		return vit;
	}
	int GetAttack(int _atk) {
    
    
		this->atk = _atk;
		return atk;
	}
	int GetDefense(int _def) {
    
    
		this->def = _def;
		return def;
	}
	RoleStateMemento* SaveState() {
    
    
		return new RoleStateMemento(vit, atk, def);
	}
	void RecoveryState(RoleStateMemento* memento) {
    
    
		this->vit = memento->GetVitality();
		this->atk = memento->GetAttack();
		this->def = memento->GetDefense();
	}
	void StateDisplay() {
    
    
		cout << "角色当前状态: " << endl;
		cout << "体力: " << this->vit << endl;
		cout << "攻击: " << this->atk << endl;
		cout << "防御: " << this->def << endl;
	}
	void GetInitState() {
    
    
		this->vit = 100;
		this->atk = 100;
		this->def = 100;
	}
	void Fight() {
    
    
		this->vit = 0;
		this->atk = 0;
		this->def = 0;
	}

private:
	int vit;
	int atk;
	int def;
};

//角色状态管理者类
class RoleStateCaretaker {
    
    
public:
	void SetMemento(RoleStateMemento* _memento) {
    
    
		this->memento = _memento;
	}
	RoleStateMemento* GetMemento() {
    
    
		return memento;
	}

private:
	RoleStateMemento* memento;
};

void test1() {
    
    
	//角色初始化
	GameRole* lixiaoyao = new GameRole;
	lixiaoyao->GetInitState();
	lixiaoyao->StateDisplay();

	//保存角色状态
	RoleStateCaretaker* stateAdmin = new RoleStateCaretaker;
	stateAdmin->SetMemento(lixiaoyao->SaveState());

	//大战BOSS后
	cout << "大战后: " << endl;
	lixiaoyao->Fight();
	lixiaoyao->StateDisplay();

	//恢复之前状态
	cout << "恢复后: " << endl;
	lixiaoyao->RecoveryState(stateAdmin->GetMemento());
	lixiaoyao->StateDisplay();

	delete stateAdmin;
	delete lixiaoyao;
}

int main() {
    
    
	test1();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/wode_0828/article/details/114285189