在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
一、概述 Subject知道它的所有观察者并提供了观察者注册和删除订阅的接口。
View Code
1 public class CreditCard : EventArgs 2 { 3 private float _spendAmount; 4 public event EventHandler<CreditCard> SpendMoney; 5 6 public float SpendAmount 7 { 8 get 9 { 10 return _spendAmount; 11 } 12 set 13 { 14 _spendAmount = value; 15 Notify(); 16 } 17 } 18 19 private void Notify() 20 { 21 if (SpendMoney != null) 22 { 23 SpendMoney(this, this); 24 } 25 } 26 } 接着定义Observer接口,并使用户帐户类和短信提醒类实现这个接口,其中这两个ConcreteObserver类的Update方法签名必须与CreditCard中的事件SendMoney一致,否则就无法注册到CreditCard。
View Code
1 public interface IObserver<T> 2 { 3 void Update(Object sender, T e); 4 } 5 6 public class SMSNotify : IObserver<CreditCard> 7 { 8 public void Update(Object sender, CreditCard e) 9 { 10 Console.WriteLine("Sms notify.Spend {0}", e.SpendAmount); 11 } 12 } 13 14 public class Account : IObserver<CreditCard> 15 { 16 private float _accountAmount; 17 18 public Account(float accountAmount) 19 { 20 _accountAmount = accountAmount; 21 } 22 23 public void Update(Object sender, CreditCard e) 24 { 25 _accountAmount += e.SpendAmount; 26 Console.WriteLine("Account amount is {0}", _accountAmount); 27 } 28 } 最后看一下客户端调用。
View Code
1 static void Main(string[] args) 2 { 3 CreditCard creditCard = new CreditCard(); 4 SMSNotify sms = new SMSNotify(); 5 Account account = new Account(1000); 6 creditCard.SpendMoney += account.Update; 7 creditCard.SpendMoney += sms.Update; 8 creditCard.SpendAmount = 200; 9 } |
请发表评论