当某一对象发生变化时,所有依赖它的对象都需要得到通知。
using System; using System.Collections; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class Program { public class CreditCard { private float money; public event EventHandler<CreditCard> spendMoney; public float Money { get { return money; } set { money = value; Notify(); } } public void Notify() { if (spendMoney != null) { spendMoney(this, this); } } } public class Phone { public void Notify(object sender, CreditCard e) { Console.WriteLine("phone notify " + e.Money); } } public class Computer { public void Notify(object sender, CreditCard e) { Console.WriteLine("computer notify " + e.Money); } } static void Main(string[] args) { CreditCard creditCard = new CreditCard(); Phone phone = new Phone(); Computer computer = new Computer(); creditCard.spendMoney += phone.Notify; creditCard.spendMoney += computer.Notify; creditCard.Money = 200; } } }