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