C#面向对象设计模式纵横谈——19 Observer观察者模式

主讲:李建忠

来源:http://www.microsoft.com/china/msdn/events/webcasts/shared/webcast/consyscourse/CsharpOOD.aspx

 

clip_image002

clip_image004

clip_image006

clip_image008

clip_image010

 

Observer

   1:  public interface IAccountObserver
   2:  {
   3:      void Upadate();
   4:  }
   5:   
   6:  public class ATM
   7:  {
   8:      BankAccount bankAccount;
   9:   
  10:      public void process()
  11:      {
  12:          bankAccount.Withdraw(data);
  13:      }
  14:  }
  15:   
  16:  public class BankAccount
  17:  {
  18:      ArrayList<IAccountObserver> observerList=new ArrayList<IAccountObserver>();
  19:   
  20:      public void Withdraw(int data)
  21:      {
  22:          //...
  23:   
  24:          userAccountArgs args=new 
  25:          foreach(IAccountObserver observer in observerList)
  26:          {
  27:              observer.Update(args);
  28:          }
  29:   
  30:      }
  31:   
  32:      public void AddObserver(IAccountObserver observer)
  33:      {
  34:          observerList.Add(observer);
  35:      }
  36:  }
  37:   
  38:  public class Emailer
  39:  {
  40:      public void SendEmail(string to)
  41:      {
  42:          //...
  43:      }
  44:  }
  45:   
  46:  public class Mobile
  47:  {
  48:      public void SendNotification(string phoneNumber)
  49:      {
  50:          //...
  51:      }
  52:  }

 

Observer Event

public delegate void AccountchangeEventhandler(

object sender, 

AccountChangeEventArgs args);



public class BankAccount

{

    public event AccountChangeEventHandler AccountChange;



    public void Withdraw(int data)

    {

        //...



        AccountChangeEventArgs args=new AccountChangeEventArgs();

        foreach(IAccountObserver observer in observerList)

        {

            observer.Update(args);

        }



    }



    protected virtual OnAccountChange()

    {

        if(AccountChange!=null)

        {

            AccountChange(args);

        }

    }

}



public class Emailer

{

    public void Update(object sender, UserAccountArgs args)

    {

        //...

    }

}



class App

{

    public static void Main()

    {

        BankAccount bankAccount=new BankAccount();



        Emailer emailer=new Emailer();

        bankAccount.AccountChange+=new AccountChangeEventHandler(emailer.Update)



        //...

        bankAccount.Withdraw(234);

    }

}

 

clip_image012

clip_image014

clip_image016

你可能感兴趣的:(observer)