摘錄自:設計模式與遊戲完美開發
十年磨一劍,作者将設計模式理論巧妙地融入到實踐中,以一個遊戲的完整實作呈現設計模式的應用及經驗的傳承 《軒轅劍》之父——蔡明宏、資深遊戲制作人——李佳澤、Product Evangelist at Unity Technologies——Kelvin Lo、信仁軟體設計創辦人—— 賴信仁、資深3D遊戲美術——劉明恺 聯合推薦全書采用了整合式的項目教學,即以一個遊戲的範例來應用23種設計模式的實作貫穿全書,讓讀者學習到整個遊戲開發的全過程和作者想要傳承的經驗,并以淺顯易懂的比喻來解析難以了解的設計模式,讓想深入了解此領域的讀者更加容易上手。
using UnityEngine;
using System.Collections;
namespace DesignPattern_ChainofResponsibility
{
// 處理訊息的介面
public abstract class Handler
{
protected Handler m_NextHandler = null;
public Handler( Handler theNextHandler )
{
m_NextHandler = theNextHandler;
}
public virtual void HandleRequest(int Cost)
{
if(m_NextHandler!=null)
m_NextHandler.HandleRequest(Cost);
}
}
// 處理所負責的訊息1
public class ConcreteHandler1 : Handler
{
private int m_CostCheck = 10;
public ConcreteHandler1( Handler theNextHandler ) : base( theNextHandler )
{}
public override void HandleRequest(int Cost)
{
if( Cost <= m_CostCheck)
Debug.Log("ConcreteHandler1.核準");
else
base.HandleRequest(Cost);
}
}
// 處理所負責的訊息2
public class ConcreteHandler2 : Handler
{
private int m_CostCheck = 20;
public ConcreteHandler2( Handler theNextHandler ) : base( theNextHandler )
{}
public override void HandleRequest(int Cost)
{
if( Cost <= m_CostCheck)
Debug.Log("ConcreteHandler2.核準");
else
base.HandleRequest(Cost);
}
}
// 處理所負責的訊息3
public class ConcreteHandler3 : Handler
{
public ConcreteHandler3( Handler theNextHandler ) : base( theNextHandler )
{}
public override void HandleRequest(int Cost)
{
Debug.Log("ConcreteHandler3.核準");
}
}
}
using UnityEngine;
using System.Collections;
using DesignPattern_ChainofResponsibility;
public class ChainofResponsibilityTest : MonoBehaviour {
// Use this for initialization
void Start () {
UnitTest();
}
//
void UnitTest () {
// 建立Cost驗証的連接方式
ConcreteHandler3 theHandle3 = new ConcreteHandler3(null);
ConcreteHandler2 theHandle2 = new ConcreteHandler2(theHandle3);
ConcreteHandler1 theHandle1 = new ConcreteHandler1(theHandle2);
// 確認
theHandle1.HandleRequest(10);
theHandle1.HandleRequest(15);
theHandle1.HandleRequest(20);
theHandle1.HandleRequest(30);
theHandle1.HandleRequest(100);
}
}