首页 > 编程语言 > 详细

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

时间:2019-10-26 11:06:06      阅读:84      评论:0      收藏:0      [点我收藏+]



概述参考请看 参考博客

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

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. 可能导致对象创建过多,开销大。

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

原文:https://www.cnblogs.com/Fflyqaq/p/11741995.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!