Saturday, October 20, 2007

Observer Pattern (5) Step By Step

In this step, we finally finish the steps to produce the observer pattern, you can see that, now we abstract the BankAccount class to a new abstract class called Subject, now strip out the common fields of BankAccount class, and move them to the Subject class. So now the if in the future there are now changes coming, we can just modify the BankAccount class, without touching the Subject class.

The overall class structure is like this:



  • Subject class is the Subject

  • BankAccount class is the ConcreteSubject

  • IAccountObserver is the observer

  • Emailer & Mobile classes are the ConcreteObserver


public abstract class Subject


{


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



public void Notify(UserAccountArgs args)


{


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 class BankAccount : Subject


{


public void Withdraw(int data)


{


//...



UserAccoutArgs args = new UserAccountArgs();


//...



Notify(args);


}


}

blog comments powered by Disqus