备忘录模式是指在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可以将该对象恢复到原先保存的状态。Memento模式比较适用于功能比较复杂的,但需要维护或记录属性历史的类,或者需要保存的属性只是众多属性中的一小部分。备忘录模式最大的作用就是当角色的状态改变时,有可能这个状态无效,这时候就可以使用暂时存储起来的备忘录将状态复原。
下面是UML图:
Originator负责创建一个备忘录,用来记录当前时刻它的内部状态,并可使用备忘录恢复内部状态。Memento负责存储Originator对象的内部状态,并可防止Originator以外的其他对象访问备忘录Memento。Caretaker负责保存好备忘录Memento,不能对备忘录的内容进行操作。
代码如下:
//Originator
class GameRole
{
private:
int vit;//生命力
int atk;//攻击力
int def;//防御力
public:
GameRole() {}
~GameRole() {}
void StateDisplay()
{
printf("角色当前状态:\n");
printf("生命力%d\n", vit);
printf("攻击力%d\n", atk);
printf("防御力%d\n", def);
}
void InitState()
{
vit = 100;
atk = 100;
def = 100;
}
void Fight()
{
vit = 0;
atk = 0;
def = 0;
}
RoleStateMemento* SaveState()
{
return ( new RoleStateMemento(vit, atk, def) );
}
void RecoveryState(RoleStateMemento* pMemento)
{
vit = pMemento->GetVit();
atk = pMemento->GetAtk();
def = pMemento->GetDef();
}
};
//Memento
class RoleStateMemento
{
private:
int vit;
int atk;
int def;
public:
RoleStateMemento(int __v, int __a, int __d)
{
vit = __v;
atk = __a;
def = __d;
}
~RoleStateMemento() {}
int GetVit()
{
return vit;
}
int GetAtk()
{
return atk;
}
int GetDef()
{
return def;
}
};
//管理类
class RoleStateCaretaker
{
private:
RoleStateMemento *m_pMemento;
public:
void SetMemento(RoleStateMemento* __m )
{
m_pMemento = __m;
}
RoleStateMemento* GetMemento()
{
return m_pMemento;
}
};
//客户端代码
int _tmain(int _tmain(int argc, TCHAR* argv[]))
{
GameRole * pGame = new GameRole();
pGame->InitState();
pGame->StateDisplay();
printf("\n");
RoleStateCaretaker *pRoleStateCare = new RoleStateCaretaker();
pRoleStateCare->SetMemento(pGame->SaveState());
pGame->Fight();
pGame->StateDisplay();
printf("\n");
pGame->RecoveryState(pRoleStateCare->GetMemento());
pGame->StateDisplay();
printf("\n");
if (pGame)
{
delete pGame;
pGame = NULL;
}
if (pRoleStateCare)
{
delete pRoleStateCare;
pRoleStateCare = NULL;
}
}