c#实现观察者模式(集合版)

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. using System.Collections;
  5. namespace ObserverDemo
  6. {
  7.     class Program
  8.     {
  9.         static void Main(string[] args)
  10.         {
  11.             BankAccount account = new BankAccount();
  12.             account.name = "aladdin";
  13.             account.money = 200;
  14.             account.AddInfo( new Mobile() );
  15.             account.AddInfo( new Email() );
  16.             account.WithDraw( 100 );
  17.             Console.Read();
  18.         }
  19.     }
  20.     abstract class ISubject
  21.     {
  22.         ArrayList arrs = new ArrayList();
  23.         public void AddInfo(IUpdate update)
  24.         {
  25.             this.arrs.Add(update);
  26.         }
  27.         public void Notify( string info )
  28.         {
  29.             //取完之后要通知各组件对象
  30.             foreach (IUpdate i in arrs)
  31.             {
  32.                 i.Update( info );
  33.             }
  34.         }
  35.     }
  36.     //银行帐户
  37.     class BankAccount : ISubject
  38.     {
  39.         public string name;
  40.         public int  money;
  41.         //取钱
  42.         public void WithDraw(int money)
  43.         {
  44.             this.money -= money;
  45.             this.Notify(string.Format("{0}:取走{1}钱,还有{2}钱"this.name, money, this.money) );
  46.         }
  47.     
  48.     }
  49.     interface IUpdate
  50.     {
  51.         void Update( string info );
  52.     }
  53.     class Mobile:IUpdate
  54.     {
  55.         public void Update( string info )
  56.         {
  57.             Console.WriteLine("Mobile被通知了" + info);
  58.         }
  59.     }
  60.     class Email : IUpdate
  61.     {
  62.         public void Update(string info )
  63.         {
  64.             Console.WriteLine( "Email被通知了" + info);
  65.         }
  66.     }
  67. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值