Unity教程合集Unity基础入门分享程序员

设计模式---责任链模式(DesignPattern_Chain

2017-08-30  本文已影响28人  su9257_海澜

摘录自:设计模式与游戏完美开发

十年磨一剑,作者将设计模式理论巧妙地融入到实践中,以一个游戏的完整实现呈现设计模式的应用及经验的传承 《轩辕剑》之父——蔡明宏、资深游戏制作人——李佳泽、Product Evangelist at Unity Technologies——Kelvin Lo、信仁软件设计创办人—— 赖信仁、资深3D游戏美术——刘明恺 联合推荐全书采用了整合式的项目教学,即以一个游戏的范例来应用23种设计模式的实现贯穿全书,让读者学习到整个游戏开发的全过程和作者想要传承的经验,并以浅显易懂的比喻来解析难以理解的设计模式,让想深入了解此领域的读者更加容易上手。


工程GitHub

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);

    
    }
}

上一篇下一篇

猜你喜欢

热点阅读