首页 > 其他 > 详细

观察者模式实现方法

时间:2020-01-20 14:51:02      阅读:60      评论:0      收藏:0      [点我收藏+]
 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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!