/* * 备忘录模式 */ #include <myhead.h> //保存值 class mySavevalue { public: mySavevalue(string user_name = "", int life_value = 100, int magic_point = 100, int rank_values = 1, int experience_value = 1000) :_user_name(user_name), _life_value(life_value), _magic_point(magic_point), _rank_values(rank_values), _experience_value(experience_value) { } mySavevalue& operator=(const mySavevalue &savevalue) { _life_value = savevalue._life_value; _magic_point = savevalue._magic_point; _rank_values = savevalue._rank_values; _experience_value = savevalue._experience_value; return *this; } public: string _user_name; //用户名(或用户id(md5值)) int _life_value; //红血 int _magic_point; //蓝学 int _rank_values; //等级 int _experience_value; //经验值 //其它值 }; //游戏角色 class Role { public: Role(string user_name, int life_value, int magic_point, int rank_values, int experience_value) :_user_name(user_name), _life_value(life_value), _magic_point(magic_point), _rank_values(rank_values), _experience_value(experience_value) {} mySavevalue Save() //保存当前值 { mySavevalue savevalue(_user_name, _life_value, _magic_point, _rank_values, _experience_value); return savevalue; } void Loadvalue(mySavevalue &savevalue) //载入之前的值 { _life_value = savevalue._life_value; _magic_point = savevalue._magic_point; _rank_values = savevalue._rank_values; _experience_value = savevalue._experience_value; } void Show() { cout << "用户 : " << _user_name.c_str() << ", 等级 : " << _rank_values << ", 红血 : " << _life_value << ", 蓝血 : " << _magic_point << ", 当前经验值 : " << _experience_value << endl; } void attack() //升级 { _magic_point -= 10; _experience_value += 250; if (_experience_value == 1000)
{ _rank_values += 1; _experience_value = 0; } } void Being_attacked() //被攻击 { _life_value -= 10; } private: string _user_name; int _life_value; int _magic_point; int _rank_values; int _experience_value; }; //保存的进度库 class LookafterSavevalue { public: LookafterSavevalue() {} void Save(string name, mySavevalue savevalue) { _mapSavevalue.insert(map<string, mySavevalue>::value_type(name, savevalue)); } mySavevalue Load(string name) { return _mapSavevalue[name]; } private: map<string, mySavevalue> _mapSavevalue; }; //测试案例 int main() { LookafterSavevalue lookaftersavevalue; Role role("role_wang", 100, 100, 0, 0); role.Show(); //初始值 lookaftersavevalue.Save("role_wang", role.Save()); //保存状态 role.attack(); role.Show(); //进攻后 lookaftersavevalue.Save("role_wang", role.Save()); //保存状态 role.Loadvalue(lookaftersavevalue.Load("role_wang")); //载入状态 role.Show(); //恢复到状态0 role.attack(); role.Show(); //进攻后 role.attack(); role.Show(); //进攻后 role.attack(); role.Show(); //进攻后 role.attack(); role.Show(); //进攻后 role.Being_attacked(); role.Show(); //被进攻后 lookaftersavevalue.Save("role_wang", role.Save()); //保存状态 role.Loadvalue(lookaftersavevalue.Load("role_wang")); //载入状态 role.Show(); //恢复到状态1 getchar(); return 0; }
原文地址:http://blog.csdn.net/skymanwww/article/details/36004169