Friday, October 19, 2007

Observer Pattern (2) Step By Step

Now we've seen the tight coupling problem in step 1. Let's think about it for a second,

  • SendEmail method of Emailer class
  • SendNotification method of Mobile class

These types of classes/methods, they have something in common:

  • They all need to send some information
  • Or you can say they all need to update some information

Now I have re-designed the class structrue:

  • BankAccount (now depends on IAccountObserve)
  • IAccountObserver
  • Emailer
  • Mobile



public class BankAccount

{

IAccountObserver emailer; //loose coupling

public void Withdraw(int data)

{

//...

UserAccountArgs args = new UserAccountArgs();

//...

emailer.Update(args);

}

}

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;

}

}

This code resolve the tight coupling problems, so the BankAccount doesn't need to be changed in order to cater for any future modification. But it only illustrates an one-to-one relationship between BankAccount class and Emailer class, the next session will explain how to implement one-to-many relationships.

blog comments powered by Disqus