观察者模式(observer行为型)c#简单例子
几个要点:模式使目标与观察都之间的依赖关系达到松耦合、通知会自动传播
例子:玩家击中敌人后发生一系列变化:发后爆炸、敌人少1个....
namespace adapterpattern{ public partial class ObserverForm : Form { public ObserverForm() { InitializeComponent(); } private void btnDisplay_Click(object sender, EventArgs e) { BaseData.EnemyNumber = 100; IObserver explosionEvent = new ExplosionEvent(); IObserver enemy = new Enemy(); player p1 = new player1(); p1.AddObserver(explosionEvent); p1.AddObserver(enemy); p1.Notify(); listBox1.Items.Add(p1.Display()); } } public static class BaseData//数据中转站 { public static string DisplayString { get; set; } public static int EnemyNumber { get; set; } } public abstract class player { List<IObserver> observers = new List<IObserver>();//观察员列表 public virtual void Notify() { foreach (IObserver observer in observers) { observer.Update();//遂个通知观察员 } } public virtual void AddObserver(IObserver observer)//增加观察员 { observers.Add(observer); } public virtual void Delet(IObserver observer)//删除观察员 { observers.Remove(observer); } public abstract string Display(); } public class player1 : player { public override string Display() { return BaseData.DisplayString + BaseData.EnemyNumber.ToString(); } } public interface IObserver//观察员接口 { void Update(); } public class ExplosionEvent : IObserver //观察员1 { public void Update() { BaseData.DisplayString = "显示爆炸"; } } public class Enemy : IObserver //观察员2 { public void Update() { BaseData.EnemyNumber -= 1; //"敌人数减少1个"; } }}