2014年1月17日 星期五

今天在大話設計模式的時候, 裡面提到C#裡的delegate用法

我看了一下,感覺它的用處應該就是利用+=( overload)

將所要被呼叫的function註冊(prototype要相同)

存放到一個貯列裡, 當一呼叫該delegate event

便走訪貯列,並呼叫被走訪到且有被註冊的fuunction

這樣的實作可以減少程式碼裡有大量foreach或other loop的存在




using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace observer
{
    delegate void EventHandler();
    interface Subject
    {
        void Notfiy();
        string SubjectState
        {
            get;
            set;
        }
    }
    class Boss : Subject
    {
        public event EventHandler Update;// 宣告一個delegate event
        private string action;
        public void Notfiy()
        {
            Update();
        }
        public string SubjectState
        {
            get { return action; }
            set { action = value; }
        }
    }
    class StockObserver
    {
        private string name;
        private Subject sub;
        public StockObserver(string name, Subject sub)
        {
            this.name = name;
            this.sub = sub;
        }
        public void CloseStockMarket()
        {
            Console.WriteLine("{0} {1}關閉股票行情,工作!", sub.SubjectState, name);
        }
    }
    class NBAObserver
    {
        private string name;
        private Subject sub;
        public NBAObserver(string name, Subject sub)
        {
            this.name = name;
            this.sub = sub;
        }
        public void CloseNBA()
        {
            Console.WriteLine("{0} {1}關閉NBA直播,工作!", sub.SubjectState, name);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Boss boss = new Boss();
            //boss.Update註冊StockObserver.CloseStockMarket
            boss.Update += new EventHandler((new StockObserver("A",boss)).CloseStockMarket);
            //boss.Update註冊NBAObserver.CloseNBA
            boss.Update += new EventHandler((new NBAObserver("B", boss)).CloseNBA);
            boss.SubjectState = "boss 回來了!";
            // 呼叫該delegate event 便可以將所有被註冊的funcion依序執行
            boss.Notfiy();
            Console.Read();
        }
       
    }
}

0 意見:

張貼留言