摘錄自:設計模式與游戲完美開發
十年磨一劍,作者將設計模式理論巧妙地融入到實踐中,以一個游戲的完整實現呈現設計模式的應用及經驗的傳承 《軒轅劍》之父——蔡明宏、資深游戲制作人——李佳澤、Product Evangelist at Unity Technologies——Kelvin Lo、信仁軟件設計創辦人—— 賴信仁、資深3D游戲美術——劉明愷 聯合推薦全書采用了整合式的項目教學,即以一個游戲的范例來應用23種設計模式的實現貫穿全書,讓讀者學習到整個游戲開發的全過程和作者想要傳承的經驗,并以淺顯易懂的比喻來解析難以理解的設計模式,讓想深入了解此領域的讀者更加容易上手。
工程GitHub
using UnityEngine;
using System.Collections.Generic;
namespace DesignPattern_Memento
{
// 存放Originator物件的內部狀態
public class Memento
{
string m_State;
public string GetState()
{
return m_State;
}
public void SetState(string State)
{
m_State = State;
}
}
// 需要儲存內容資訊
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();
}
}
// 保管所有的Memento
public class Caretaker
{
Dictionary<string, Memento> m_Memntos = new Dictionary<string, Memento>();
// 增加
public void AddMemento(string Version , Memento theMemento)
{
if(m_Memntos.ContainsKey(Version)==false)
m_Memntos.Add(Version, theMemento);
else
m_Memntos[Version]=theMemento;
}
// 取回
public Memento GetMemento(string Version)
{
if(m_Memntos.ContainsKey(Version)==false)
return null;
return m_Memntos[Version];
}
}
}
using UnityEngine;
using System.Collections;
using DesignPattern_Memento;
public class MementoTest : MonoBehaviour {
// Use this for initialization
void Start () {
UnitTest();
UnitTest2();
}
//
void UnitTest () {
Originator theOriginator = new Originator();
// 設定資訊
theOriginator.SetInfo( "Step1" );
theOriginator.ShowInfo();
// 儲存狀態
Memento theMemnto = theOriginator.CreateMemento();
// 設定新的資訊
theOriginator.SetInfo( "Step2" );
theOriginator.ShowInfo();
// 復原
theOriginator.SetMemento( theMemnto );
theOriginator.ShowInfo();
}
//
void UnitTest2 () {
Originator theOriginator = new Originator();
Caretaker 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.SetMemento( theCaretaker.GetMemento("2"));
theOriginator.ShowInfo();
// 退回到第1版,
theOriginator.SetMemento( theCaretaker.GetMemento("1"));
theOriginator.ShowInfo();
}
}