- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace ObserverDemo
- {
- class 观查者模式委托版
- {
- public static void Main(string[] args)
- {
- BankAccount count = new BankAccount();
- count.WithDrawEvent += new BankAccount.WithDrawEventHandler( new Email().Update);
- count.WithDraw(50);
- Console.Read();
- }
- }
- abstract class ISubject
- {
- public delegate void WithDrawEventHandler(object sender, UserMsgInfoEventArgs args);
- public event WithDrawEventHandler WithDrawEvent;
- public void OnWithDrawEvent(UserMsgInfoEventArgs args)
- {
- if (this.WithDrawEvent != null)
- {
- this.WithDrawEvent(this, args);
- }
- }
- }
- class BankAccount : ISubject
- {
- public int money = 90 ;
- public void WithDraw( int money )
- {
- this.money -= money;
- OnWithDrawEvent(new UserMsgInfoEventArgs(string.Format("取走{0}钱,还有{1}钱", money, this.money)));
- }
- }
- class UserMsgInfoEventArgs : EventArgs
- {
- //传送信息
- public string sendinfo;
- public UserMsgInfoEventArgs(string info)
- {
- this.sendinfo = info;
- }
- }
- class Email
- {
- public void Update(object sender, UserMsgInfoEventArgs args)
- {
- Console.WriteLine( args.sendinfo );
- }
- }
- }