观察者模式生活中的一个应用

时间:2022-09-21 20:43:33

场景:当公司每个月向你支付工资的时候,将会向你发送一条短信通知

Step1:首先,我们需要定义一个委托,通过委托将两个类的交互进行了绑定,当公司转账的方法Gapes()调用后,触发委托类型的SaveMoney事件,而该事件将被委托给用户(User)的通知(Notify)方法处理

// <summary>
   ///定义代理
   /// </summary>
   /// <param name="sender"></param>
   /// <param name="e"></param>
   public delegate void DelegateMonitorCustomer(object sender, CustomerEventArgs e);
  
    /// <summary>
    /// 银行卡
    /// </summary>
   public class Account
    {
       /// <summary>
       /// 转帐人姓名
       /// </summary>
       public string  Sender { get; set; }
       //转账金额
       public  decimal Money { get; set; }

       public event DelegateMonitorCustomer SaveMoney;
       public void Gapes()
       {
           CustomerEventArgs e = new CustomerEventArgs();
           e.Sender = this.Sender;
           e.Money = this.Money;
           SaveMoney(this, e);
       }
      
    }

   public class CustomerEventArgs : EventArgs
   {
       public string Sender { get; set; }
       public decimal Money { get; set; }
   }

public class User
    {
       public void Notify(object sender,CustomerEventArgs e)
       {
           StringBuilder resutl = new StringBuilder();
           resutl.Append(e.Sender+"向您的卡中转入"+e.Money+"元钱");
           resutl.Append("时间:" + DateTime.Now.ToString());
           Console.WriteLine(resutl);

       }
    
    }

 

  class Program
    {
        static void Main(string[] args)
        {
            Account account = new Account();
            account.Sender = "爱施德股份";
            account.Money = 5000;
            User box=new User();
            account.SaveMoney+=new DelegateMonitorCustomer(box.Notify);
            account.Gapes();
        }

     
    }