c#中观查者模式实现(委托版)

本文介绍了一种基于C#的观察者模式实现方法,通过委托和事件来通知多个观察者对象更新状态。示例中使用银行账户取款事件触发邮件通知作为应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace ObserverDemo
  5. {
  6.     class 观查者模式委托版
  7.     {
  8.         public static void Main(string[] args)
  9.         {
  10.             BankAccount count = new BankAccount();
  11.             count.WithDrawEvent += new BankAccount.WithDrawEventHandler( new Email().Update);
  12.             count.WithDraw(50);
  13.             Console.Read();
  14.         }
  15.     }
  16.     abstract class ISubject
  17.     {
  18.         public delegate void WithDrawEventHandler(object sender, UserMsgInfoEventArgs args);
  19.         public event WithDrawEventHandler WithDrawEvent;
  20.         public void OnWithDrawEvent(UserMsgInfoEventArgs args)
  21.         {
  22.             if (this.WithDrawEvent != null)
  23.             {
  24.                 this.WithDrawEvent(this, args);
  25.             }
  26.         }
  27.     }
  28.     class BankAccount : ISubject
  29.     {
  30.         public int money = 90 ;        
  31.         
  32.         public void WithDraw( int money )
  33.         {
  34.             this.money -= money;
  35.             OnWithDrawEvent(new UserMsgInfoEventArgs(string.Format("取走{0}钱,还有{1}钱", money, this.money)));
  36.         }
  37.     }
  38.     class UserMsgInfoEventArgs : EventArgs
  39.     {
  40.         //传送信息
  41.         public string sendinfo;
  42.         public UserMsgInfoEventArgs(string info)
  43.         {
  44.             this.sendinfo = info;
  45.         }
  46.     }
  47.     class Email
  48.     {
  49.         public void Update(object sender, UserMsgInfoEventArgs args)
  50.         {
  51.             Console.WriteLine( args.sendinfo );
  52.         }
  53.     }
  54. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值