观察者模式
在一对多的情况下,可以让多绑定到一的事件上。从而实现多个观察者获取通知。
class Program
{
public static void Run()
{
Husky worker = new Husky();
Engineer engineer = new Engineer();
DoorKeeper doorKeeper = new DoorKeeper();
doorKeeper.Update += worker.Update;
doorKeeper.Update += engineer.Update;
doorKeeper.meg = "有人来了!";
doorKeeper.Notify();
Console.WriteLine("过了一会");
Customer customer = new Customer();
customer.Update += worker.Update;
customer.Update += engineer.Update_Client_Arrived;
customer.meg = "我是甲方,来提要求了";
customer.Notify();
}
}
public abstract class BaseWorker
{
public string Name;
public string Status;
public virtual void Update(string meg)
{
Console.WriteLine(meg + " "+ Name+ " 返回工作岗位.");
}
}
public class Husky : BaseWorker
{
public Husky()
{
base.Name = "钻井工人";
base.Status = "摸鱼";
}
}
public class Engineer : BaseWorker
{
public Engineer()
{
base.Name = "工程师";
base.Status = "伏案工作";
}
public override void Update(string meg)
{
Console.WriteLine(meg + " " + Name + " 继续工作");
}
public void Update_Client_Arrived(string meg)
{
Console.WriteLine(meg + " " + Name + " 出门迎接");
}
}
public abstract class BaseNotifier
{
public string meg;
public delegate void Update_NomalPeople_Event(string meg);
public event Update_NomalPeople_Event Update;
public void Notify()
{
Update(meg);
}
}
public class DoorKeeper : BaseNotifier
{
}
public class Customer : BaseNotifier
{
}