zoukankan      html  css  js  c++  java
  • 观察者模式实现方法

     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);
            }
        }
  • 相关阅读:
    关于ssh的一篇很好的文章
    课后作业--2 阅读计划及问题
    课后作业--1
    课后作业PPT 7
    大道至简 7、8、读后感
    第六章 读后感
    第五篇 读后感
    数组课后作业
    课后作业1:字串加密
    第四篇 读后感
  • 原文地址:https://www.cnblogs.com/Angdybo/p/12217552.html
Copyright © 2011-2022 走看看