观察者模式实现方法

 class Program
    {
        static void Main(string[] args)
        {
            BankAccount account = new BankAccount();
            account.name = "aladdin";
            account.money = 200;
            account.AddInfo(new Mobile());
            account.AddInfo(new Email());
            account.WithDraw(100);
            Console.Read();
        }
    }
    abstract class ISubject
    {
        ArrayList arrs = new ArrayList();
        public void AddInfo(IUpdate update)
        {
            this.arrs.Add(update);
        }
        public void Notify(string info)
        {
            //取完之后要通知各组件对象
            foreach (IUpdate i in arrs)
            {
                i.Update(info);
            }
        }
    }
    //银行帐户
    class BankAccount : ISubject
    {
        public string name;
        public int money;
        //取钱
        public void WithDraw(int money)
        {
            this.money -= money;
            this.Notify(string.Format("{0}:取走{1}钱,还有{2}钱", this.name, money, this.money));
        }

    }
    interface IUpdate
    {
        void Update(string info);
    }
    class Mobile : IUpdate
    {
        public void Update(string info)
        {
            Console.WriteLine("Mobile被通知了" + info);
        }
    }
    class Email : IUpdate
    {
        public void Update(string info)
        {
            Console.WriteLine("Email被通知了" + info);
        }
    }
原文地址:https://www.cnblogs.com/Angdybo/p/12217552.html