Unity---游戏设计模式(16)之备忘录模式




概述参考请看 参考博客

备忘录模式:在不破坏封装性的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态,这样以后就可以将该对象恢复到原来保存的状态。

1、备忘录模式原型

备忘录模式原型UML

备忘录模式原型代码

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Client : MonoBehaviour
{
    private void Start () {
        //利用备忘录模式记录角色血量变化

        CareTaker careTaker = new CareTaker();
        Originator originator = new Originator();

        originator.SetHP(100);
        originator.ShowHP();
        careTaker.AddMemento("V1.0", originator.CreateMemento());

        originator.SetHP(80);
        originator.ShowHP();
        careTaker.AddMemento("V2.0", originator.CreateMemento());

        originator.SetHP(60);
        originator.ShowHP();
        careTaker.AddMemento("V3.0", originator.CreateMemento());

        originator.SetMemento(careTaker.GetMemento("V1.0"));
        originator.ShowHP();
    }
}

/// <summary>
/// 发起人---负责创建一个备忘录Memento
/// </summary>
public class Originator
{
    private int mHP;

    public void SetHP(int hp)
    {
        mHP = hp;
    }

    public void ShowHP()
    {
        Debug.Log("当前HP:" + mHP);
    }

    /// <summary>
    /// 创造一个备忘录对象,用于在CareTaker中保存
    /// </summary>
    public Memento CreateMemento()
    {
        Memento memento = new Memento();
        memento.SetHP(mHP);
        return memento;
    }

    /// <summary>
    /// 获取Memento对象,并根据里面的内容设置当前的HP
    /// 类似还原之前的版本
    /// </summary>
    public void SetMemento(Memento memento)
    {
        SetHP(memento.GetHP());
    }
}

/// <summary>
/// 备忘录
/// </summary>
public class Memento
{
    private int mHP;

    public void SetHP(int hp)
    {
        mHP = hp;
    }
    public int GetHP()
    {
        return mHP;
    }
}

/// <summary>
/// 保存所有历史备忘录对象
/// </summary>
public class CareTaker
{
    /// <summary>
    /// key:版本。value:此版本下的血量
    /// </summary>
    private Dictionary<string, Memento> mMementoDict;

    public CareTaker()
    {
        mMementoDict = new Dictionary<string, Memento>();
    }

    public void AddMemento(string version, Memento memento)
    {
        if (mMementoDict.ContainsKey(version) == false)
        {
            mMementoDict.Add(version, memento);
            return;
        }
        Debug.Log("已经存在此版本:" + version);
    }

    public Memento GetMemento(string version)
    {
        if (mMementoDict.ContainsKey(version))
        {
            return mMementoDict[version];
        }
        Debug.Log("不存在此版本:" + version);
        return null;
    }
}

2、备忘录模式优缺点

优点

  1. 更好的封装性。
  2. 可以利用备忘录恢复之前的状态。

缺点

  1. 可能导致对象创建过多,开销大。
posted @ 2019-10-26 10:14  Fflyqaq  阅读(291)  评论(0编辑  收藏  举报