【Unity与23种设计模式】备忘录模式(Memento)

GoF中定义:

“在不违反封装的原则下,获取一个对象的内部状态并保留在外部,让对象可以在日后恢复到原先保留时的状态。”

对于一些需要存储的数据,比如历史最高分

当与得分减分系统写入一个类时,违反了单一职责原则

最好是做一个SaveData的类单独存储或获取

而当使用一个单独的类时,又必须将数据public向外公开

这就将游戏置于危险的境地,甚至是方便了外挂横行

针对此矛盾局势

备忘录模式便解决了这一问题

备忘录模式可以描述为:

在不增加各个游戏系统类成员的“存取”方法的前提之下

存盘功能要能够获取各个游戏系统内部需要保存的信息

然后再游戏重新开始时,再将记录读取,并重新设置给各个游戏系统

备忘录模式的原理是:

游戏系统提供存取内部成员的方法,是让游戏系统处于“被动”状态

备忘录模式则是将游戏系统由“被动”改为“主动”提供

意思是让游戏系统自己决定要提供什么信息和记录存盘功能

也由游戏系统决定要从存盘功能中,读取什么样的数据及记录还原给内部成员

//需要存储的内容信息
public class Originator {
    string m_State;//需要被保存的状态

    public void SetInfo(string State) {
        m_State = State;
    }

    public void ShowInfo() {
        Debug.Log("Originator State:" + m_State);
    }

    public Memento CreateMemento() {
        Memento newMemento = new Memento();
        newMemento.SetState(m_State);
        return newMemento;
    }

    public void SetMemento(Memento m) {
        m_State = m.GetState();
    }
}
//存放Originator对象的内部状态
public class Memento {
    string m_State;

    public string GetState() {
        return m_State;
    }

    public void SetState(string State) {
        m_State = State;
    }
}
//测试类
public class TestMemento {
    void UnitTest() {
        Originator theOriginator = new Originator();

        theOriginator.SetInfo("Step1");
        theOriginator.ShowInfo();

        Memento theMemento = theOriginator.CreateMemento();

        theOriginator.SetInfo("Step2");
        theOriginator.ShowInfo();

        theOriginator.SetMemento(theMemento);
        theOriginator.ShowInfo();
    }
}
//Originator State:Info:Step1
//Originator State:Info:Step2
//Originator State:Info:Step1

文章整理自书籍《设计模式与游戏完美开发》 菜升达 著

原文地址:https://www.cnblogs.com/fws94/p/7457375.html