C++备忘录模式
在读《大话设计模式》,在此记录有关C++实现备忘录模式。
场景引入:游戏中的存档,比如打boss之前记录人物的血量等状态。
下面代码是自己根据理解实现的存档人物血量功能。
#include <iostream>
using namespace std;
//声明玩家类
class GamePlayer {
public:
GamePlayer(int volume = 100) :bloodVolume(volume) {};
void setBloodVolume(int volume) {
bloodVolume = volume;
};
void decreaseBloodVolume(int volume) {
if (bloodVolume < volume)
{
bloodVolume = 0;
}
else {
bloodVolume = bloodVolume - volume;
}
}
int getBloodVolume() {
return bloodVolume;
};
void showBloodVolume() {
std::cout << "当前角色血量为" << bloodVolume << std::endl;
}
private:
int bloodVolume; //血量
};
//声明备忘录类
class memorandum {
public:
void setMemor(GamePlayer& setPlayer)
{
std::cout << "正在存档..." << std::endl;
this->player.setBloodVolume(setPlayer.getBloodVolume());
}
void getMemor(GamePlayer& getPlayer)
{
std::cout << "正在读档..." << std::endl;
getPlayer.setBloodVolume(player.getBloodVolume());
}
private:
GamePlayer player;
};
int main()
{
GamePlayer player(60);
player.showBloodVolume();
memorandum playerMemory;
//存档
playerMemory.setMemor(player);
//模拟玩家受到攻击
player.decreaseBloodVolume(20);
player.showBloodVolume();
//回档
playerMemory.getMemor(player);
player.showBloodVolume();
return 0;
}
上面这段代码,声明了一个备忘录类,传入要存档的对象,获取其数据,临时存储在private的成员变量中。读档的时候引用传入玩家类,根据需要拷贝原先存储的数据。但是如果这时候需要添加蓝量相关的数据存储,需要修改的代码很多,首先是备忘录类中函数获取的数据要修改。然后玩家类中要新添加操作蓝量对应的接口。将备忘录类放在玩家类中,可以避免这些接口的声明
代码如下:
#include <iostream>
#include <memory>
using namespace std;
//声明玩家类
class GamePlayer {
public:
GamePlayer(int volume = 100) :bloodVolume(volume) {};
//声明备忘录类
class memorandum {
public:
int bloodVolume;
memorandum(int bloodNum) :bloodVolume(bloodNum) {};
};
void setBloodVolume(int volume) {
bloodVolume = volume;
};
void decreaseBloodVolume(int volume) {
if (bloodVolume < volume)
{
bloodVolume = 0;
}
else {
bloodVolume = bloodVolume - volume;
}
}
int getBloodVolume() {
return bloodVolume;
};
void showPlayerState() {
std::cout << "当前角色血量为" << bloodVolume << std::endl;
}
//存档
void savePlayerState() {
std::cout << "存档中..." << std::endl;
memor = std::make_shared<memorandum>(bloodVolume);
}
void readPlayerState() {
std::cout << "读档中..." << std::endl;
bloodVolume = memor->bloodVolume; //读取人物血量
}
private:
int bloodVolume; //血量
std::shared_ptr<memorandum> memor;
};
int main()
{
GamePlayer player(60);
player.showPlayerState();
player.savePlayerState();
//模拟玩家受到攻击
player.decreaseBloodVolume(20);
player.showPlayerState();
//读档档
player.readPlayerState();
player.showPlayerState();
//再次受到攻击
player.decreaseBloodVolume(10);
player.savePlayerState();
player.readPlayerState(); //读档
player.showPlayerState(); //展示当前数据
return 0;
}
这时,如果存档和读档更多的数据比如蓝量,怒气值,经验等,客户端代码不需要修改,仅需要修改玩家类中的代码。