作者:翟天保Steven
版权声明:著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处
备忘录模式是一种行为型的软件设计模式,在不破坏封装的前提下,获取一个对象的内部状态,并在对象外保存该状态,当对象需要恢复到该状态时,对其进行恢复。
备忘录模式的优点:
备忘录模式的缺点:
客户端即Main主函数,游戏的进度放在备忘录中,由备忘录管理类管理。
场景描述:玩游戏通关后保存进度,后面还可以加载重玩。
//Memento.h
/****************************************************/
#pragma once
#include <iostream>
#include <unordered_map>
#include <vector>
#include <list>
#include <string>using namespace std;// 备忘录类-游戏进度
class Memento
{
public:// 构造函数Memento(string state) : m_state(state) {}// 获取状态std::string getState() const{ return m_state;}private:std::string m_state;
};// 发起类-游戏
class Game
{
public:// 设置状态void setState(string state) { m_state = state;}// 获取状态string getState() { return m_state;}// 保存状态至备忘录Memento saveStateToMemento() { return Memento(m_state); }// 从备忘录获取状态void getStateFromMemento(const Memento& memento) { m_state = State(); }private:std::string m_state;
};// 备忘录管理类-进度管理
class CareTaker
{
public:// 添加备忘录void addMemento(const Memento& memento) { m_mementos.push_back(memento);}// 获取备忘录Memento getMemento(int index) { return m_mementos[index];}private:std::vector<Memento> m_mementos;
};
//main.cpp
/****************************************************/
#include <iostream>
#include <string>
#include "Memento.h"using namespace std;int main()
{Game game;CareTaker careTaker;// 通关game.setState("进度:第一关通过");game.setState("进度:第二关通过");// 保存进度,进度被管理系统管理careTaker.addMemento(game.saveStateToMemento());// 继续通关game.setState("进度:第三关通过");// 保存进度,进度被管理系统管理careTaker.addMemento(game.saveStateToMemento());// 继续通关game.setState("进度:第四关通过");// 当前进度cout << "当前" << State() << endl;// 获取首个进度Memento(0));cout << "1)" << State() << endl;// 获取第二个进度Memento(1));cout << "2)" << State() << endl;return 0;
}
程序结果如下。
游戏通过第二关后保存进度,这是进度一;通过第三关后又一次保存进度,这是进度二;通过第四关后想要重玩进度一,就加载了进度一,此时进度变为刚通过第二关的状态;加载进度二,也是一样。
我尽可能用较通俗的话语和直观的代码例程,来表述我对备忘录模式的理解,或许有考虑不周到的地方,如果你有不同看法欢迎评论区交流!希望我举的例子能帮助你更好地理解备忘录模式。
如果文章帮助到你了,可以点个赞让我知道,我会很快乐~加油!
本文发布于:2024-02-03 05:27:40,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170690926048945.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |