标签:
// Design Pattern.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include <iostream> #include <vector> using namespace std; //玩家存档类,备份,相当于模式中的Memento class PlayerMemento { //这里我们将其作为Player类的友元类,可以直接访问其private变量 friend class Player; private: int m_hp; //血量 int m_ATK; //攻击 int m_DEF; //防御 public: PlayerMemento(int hp, int atk, int def) : m_hp(hp), m_ATK(atk), m_DEF(def) { } }; //存档点,存储备忘录的地方,相当于Caretake class CheckPoint { private: vector<PlayerMemento*> m_MementoVector; public: //存档 void Save(PlayerMemento* memento) { m_MementoVector.push_back(memento); } //根据存档编号获得存档 PlayerMemento* Load(int num) { return m_MementoVector[num]; } //表忘了清空对象 void Clear() { for (vector<PlayerMemento*>::iterator it = m_MementoVector.begin(); it != m_MementoVector.end(); ++it) { delete *it; } m_MementoVector.resize(0); } }; //玩家类,就是我们需要备份的类,相当于备忘录模式里面的Originator. class Player { private: int m_hp; //血量 int m_ATK; //攻击 int m_DEF; //防御 public: Player(int hp, int atk, int def) : m_hp(hp), m_ATK(atk), m_DEF(def) { } PlayerMemento* Save() { cout << "要去打Boss了,好紧张,存个档!" << endl; return new PlayerMemento(m_hp, m_ATK, m_DEF); } void Load(PlayerMemento* memento) { m_hp = memento->m_hp; m_ATK = memento->m_ATK; m_DEF = memento->m_DEF; cout << "哇咔咔,有存档,SL大法好!" << endl; } void Display() { cout << "当前生命: " << m_hp << " 当前攻击: " << m_ATK << " 当前防御: " << m_DEF << endl; } //受伤,减血 void Hurt(int v) { m_hp -= v; if (m_hp <= 0) { m_hp = 0; cout << "OMG!我挂了!" << endl; } } }; int _tmain(int argc, _TCHAR* argv[]) { //创建一个玩家对象,以及一个存档点对象 Player* player = new Player(100, 200, 300); CheckPoint* checkPoint = new CheckPoint(); player->Display(); //每逢Boss必存档 checkPoint->Save(player->Save()); //受到10000点伤害,被boss秒了 player->Hurt(10000); player->Display(); //我有存档,我任性! player->Load(checkPoint->Load(0)); player->Display(); system("pause"); return 0; }结果:
标签:
原文地址:http://blog.csdn.net/puppet_master/article/details/51330839