备忘录模式
其他二十三种设计模式
#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());
cout << "大战后: " << endl;
lixiaoyao->Fight();
lixiaoyao->StateDisplay();
cout << "恢复后: " << endl;
lixiaoyao->RecoveryState(stateAdmin->GetMemento());
lixiaoyao->StateDisplay();
delete stateAdmin;
delete lixiaoyao;
}
int main() {
test1();
return 0;
}