備忘錄模式
前序
相信玩游戲每個人都會,今天就來講講關于游戲進度的保存機制,也就是備忘錄模式。
備忘錄模式
在不破壞封裝性的前提下,捕獲一個對象的內部狀態,兵在該對象之外保存這個狀態。這樣以后就可以將該對象恢復到原先保存的狀態。
實現方式(UML類圖)

實現代碼
#include <stdio.h>
// 角色狀態存信息
class RoleStateMemento
{
public:
int vit;
int atk;
int def;
int level;
int pass;
RoleStateMemento(int _vit, int _atk, int _def, int _level, int _pass) : vit(_vit), atk(_atk), def(_def), level(_level), pass(_pass){}
};
// 游戲角色
class GameRole : public RoleStateMemento
{
public:
GameRole() : RoleStateMemento(100, 100, 100, 1, 1) {}
RoleStateMemento* SaveState()
{
return new RoleStateMemento(vit, atk, def, level, pass);
}
void RecoveryState(RoleStateMemento* pMemento)
{
vit = pMemento->vit;
atk = pMemento->atk;
def = pMemento->def;
level = pMemento->level;
pass = pMemento->pass;
}
void Fight()
{
vit -= 20; // 第一關損失了20點血
pass++;
vit -= 40; // 第二關損失了40點血
level++; // 升級了
atk++;
def++;
pass++;
vit = 0; // 第三關直接被Boss干掉了
}
void StateDisplay()
{
printf("當前血量: %d\n", vit);
printf("當前攻擊力: %d\n", atk);
printf("當前防御力: %d\n", def);
printf("當前等級: %d\n", level);
printf("當前關卡: %d\n\n", pass);
}
};
// 角色狀態管理者
class RoleStateCaretaker
{
public:
RoleStateMemento* pMemento;
};
int main()
{
// 大戰Boss前
GameRole* lixiaoyao = new GameRole();
// 保存進度
RoleStateCaretaker* stateAdmin = new RoleStateCaretaker();
stateAdmin->pMemento = lixiaoyao->SaveState();
// 大戰Boss時,直接被干掉了
lixiaoyao->Fight();
lixiaoyao->StateDisplay();
// 恢復之前的進度
if(lixiaoyao->vit == 0)
{
lixiaoyao->RecoveryState(stateAdmin->pMemento);
lixiaoyao->StateDisplay();
}
delete stateAdmin->pMemento;
delete stateAdmin;
delete lixiaoyao;
return 0;
}
運行結果

所有文件打包下載
posted on 2011-11-13 23:48
lwch 閱讀(2705)
評論(1) 編輯 收藏 引用 所屬分類:
設計模式