备忘录模式(Memento):在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到之前保存的状态。
备忘录模式比较适用于功能较复杂的,但需要维护和记录属性历史的类,或者需要保存的属性只是众多属性中的一小部分。如果某个系统中使用命令模式时,需要实现命令的撤销功能,那么备忘录模式可以存储可撤销操作的状态。
#ifndef MEMENTO_H #define MEMENTO_H #include<iostream> #include<string> using namespace std; class RoleStateMemento; class GameRole { friend class RoleStateMemento; int vit; int atk; int dfs; public: GameRole():vit(100),atk(100),dfs(100){} //void Initial(); void Fight1(); void Fight2(); void RecoveryState(RoleStateMemento m); RoleStateMemento SaveState(); void StateDisplay(); }; class RoleStateMemento { friend class GameRole; int vit; int atk; int dfs; public: RoleStateMemento(){} RoleStateMemento(GameRole role); }; class RoleStateDirector { RoleStateMemento memento; public: RoleStateDirector(GameRole role); RoleStateDirector(RoleStateMemento role); RoleStateMemento ReturnMemento(); }; void GameRole::Fight1() { vit = 80; atk = 60; dfs = 50; } void GameRole::Fight2() { vit = 30; atk = 40; dfs = 40; } void GameRole::RecoveryState(RoleStateMemento m) { vit = m.vit; atk = m.atk; dfs = m.dfs; } RoleStateMemento GameRole::SaveState() { return RoleStateMemento(*this); } void GameRole::StateDisplay() { cout << "Vitality: " << vit << endl; cout << "Attack: " << atk << endl; cout << "Defense: " << dfs << endl; } RoleStateMemento::RoleStateMemento(GameRole role) { vit = role.vit; atk = role.atk; dfs = role.dfs; } RoleStateDirector::RoleStateDirector(GameRole role):memento(role){} RoleStateDirector::RoleStateDirector(RoleStateMemento role) : memento(role){} RoleStateMemento RoleStateDirector::ReturnMemento() { return memento; } #endif
#include"Memento.h" int main() { GameRole Xie; Xie.StateDisplay(); Xie.Fight1(); Xie.StateDisplay(); RoleStateDirector Dir(Xie.SaveState()); Xie.Fight2(); Xie.StateDisplay(); Xie.RecoveryState(Dir.ReturnMemento()); Xie.StateDisplay(); return 0; }
原文地址:http://blog.csdn.net/shiwazone/article/details/45691043