标签: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#简单例子
标签:ar io os sp for on 数据 art bs
原文地址:http://blog.csdn.net/zhgl7688/article/details/41989495