【设计模式】备忘录模式

该文章介绍了使用备忘录模式在Unity3D中实现游戏进度的保存和回档。Originator类负责创建和恢复信息,Memento类用于封装状态,而Caretaker类管理这些备忘录,允许游戏在不同版本间切换。
摘要由CSDN通过智能技术生成

原理:Mem(信息类,负责封装需要保存的信息),Origin(发起者,也就是当前状态),Care(管理类,负责将Mem暂存)。需要保存时,Origin类new一个Mem,保存当前状态,发送给Care。回档时将Care赋值给Origin。

参考代码:(4条消息) Unity3D 设计模式学习之备忘录模式_unity 备忘录模式 游戏存档_liaoshengg的博客-CSDN博客

暂存游戏进度:

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(){
        Memeto newMemento = new Memento();
        newMemento.SetState(m_State);
        return newMemento;
    }
    //设置要恢复的记录
    public void SetMemento(Memento m){
        m_State = m.GetState();
    }
}
public class Memento{
    string m_State;
    public string GetState(){
        return m_State;
    }
    public void SetState(string State){
        m_State = State;
    }
}
public class Caretaker{
    Dictionary<string,Memento> m_Mementos = new Dictionary<string,Memento>();
    //增加
    public void AddMemento(string Version,Memento theMemento){
        if(m_Mementos.ContainsKey(Version) == false) 
            m_Menmentos.Add(Version,theMemento);
        else{
            m_Mementos[Version] = theMemento;
        }
    }
    //读取
    public Memento GetMemento(string Version){
        if(m_Nementos.CointainsKey(Version)) == false){
            return null;
        }
        return m_Mementos[Version];
    }
}
void UnitTest(){
    Originator theOriginator = new Originator();
    CareteKer theCaretaker = new Caretaker();

    //设置信息
    theOriginator.SetInfo("Version1");
    theOriginator.ShowInfo();
    //保存
    theCaretaker.AddMemento("1",theOriginator.CreateMemento());

    //设置信息
    theOriginator.SetInfo("Version2");
    theOriginator.ShowInfo();
    //保存
    theCaretaker.AddMemento("2",theOriginator.CreateMemento());

    //设置信息
    theOriginator.SetInfo("Version3");
    theOriginator.ShowInfo();
    //保存
    theCaretaker.AddMemento("3",theOriginator.CreateMemento());

    ///退回到第2版
    theOriginator.SetMementor(theCaretaker.GetMemento("2"));
    theOriginator.ShowInfo();
    //退回到第1版
    theOriginator.SetMemento(theCaretaker.GetMemento("1"));
    theOriginator.ShowInfo();
}

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值