觀察者模式(observer)之委託(delegate) c#簡單例子

來源:互聯網
上載者:User

標籤:ar   io   os   sp   for   on   資料   art   bs   

觀察者模式(observer)之委託(delegate) c#簡單例子

幾個要點:模式使目標與觀察都之間的依賴關係達到松耦合、通知會自動傳播
例子:玩家擊中敵人後發生一系列變化:發後爆炸、敵人少1個....


namespace adapterpattern{    public partial class observerDelegateForm : Form    {        public observerDelegateForm()        {            InitializeComponent();            BaseData.EnemyNumber = 100;        }        private void btnDisplay_Click(object sender, EventArgs e)        {            ExplosionEvent explosionEvent = new ExplosionEvent();//觀察員1            Enemy enemy = new Enemy();//觀察員2            player p1 = new player1();            p1.Update += new EventHandler(explosionEvent.ExplosionMax);//委託加入觀察員1            p1.Update += new EventHandler(enemy.Decrease);//委託中加入觀察員2            listBox1.Items.Add(p1.Display());        }    }    public static class BaseData//資料中轉站    {        public static string DisplayString { get; set; }        public static int EnemyNumber { get; set; }    }    public delegate void EventHandler();//事件處理常式的委託    public abstract class player    {        public event EventHandler Update;//聲明一事件update        protected virtual void Notify()//對加入事件執行通知        {            if (Update != null)            {               Update ();            }        }        public abstract string Display();    }    public class player1 : player    {        public override string Display()        {             Notify ();//通知觀察員;            return BaseData.DisplayString + BaseData.EnemyNumber.ToString();        }    }    public class ExplosionEvent  //觀察員1    {        public void ExplosionMax()        {            BaseData.DisplayString = "顯示大爆炸";        }        public void ExplosionMin()        {            BaseData.DisplayString = "顯示小爆炸";          }        //.....    }    public class Enemy  //觀察員2    {        public void Decrease()        {            BaseData.EnemyNumber -= 1;       //"敵人數減少1個";         }        //.....    }}


觀察者模式(observer)之委託(delegate) c#簡單例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.