Saturday, October 20, 2007

Observer Pattern (3) Step By Step

Now we've come to step 3, the code for this step mainly resolve the problem with one-to-many relationships.
Now it's time to define what observer pattern is:

Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.

This code has already shown part of the observer pattern:

  • BankAccount class is the subject

  • IAccountObserver is the observer

  • Emailer & Mobile classes are the ConcreteObserver

The code changed compared to step 2 is highlighted in Bold:


public class BankAccount


{


ArrayList<IAccountObserver> observerList = new ArrayList<IAccountObserver>();



public void Withdraw(int data)


{


//...



UserAccountArgs args = new UserAccountArgs();


//...



foreach (IAccountObserver observer in observerList)


{


observer.Update(args);


}


}



public void AddObserver(IAccountObserver observer)


{


observerList.Add(observer);


}



public void RemoveObserver(IAccountObserver observer)


{


observerList.Remove(observer);


}


}



public interface IAccountObserver


{


void Update(UserAccountArgs args);


}



public class Emailer : IAccountObserver


{


public void Update(UserAccountArgs args)


{


//...


string toAddress = args.ToAddress;


}


}



public class Mobile : IAccountObserver


{


public void Update(UserAccountArgs args)


{


//...


string mobileNumber = args.MobileNumber;


}


}

blog comments powered by Disqus