Friday, October 19, 2007

Observer Pattern (1) Step By Step

Now it's time for us to explore observer patterns into greater details, we'll first discuss how things are done without the pattern.

Assume there are two ways for us to withdraw money from our bank account:
  • Send an email to the bank
  • Call bank via mobile phone
We have the following class structures:
  • BankAccount class (depends on Emailer & Mobile)
  • Emailer class
  • Mobile class

This is how we implement this dependency among these three classes without using design patterns, the problem with this design is:

  • Say now we have a new way to withdraw money
  • We need to change the Withdraw method of the BankAccount
  • This is not what we want, we want the BankAccount class to be close for modification and open for extension

public class BankAccount

{

Emailer emailer; //Tight coupling

Mobile mobile; //Tight coupling

public void Withdraw(int data)

{

//...

string userEmail = "samf@elcom.com.au";

string phoneNumber = "12345678";

//...

emailer.SendEmail(userEmail);

mobile.SendNotification(phoneNumber);

}

}

public class Emailer

{

public void SendEmail(string to)

{

//...

}

}

public class Mobile

{

public void SendNotification(string phoneNumber)

{

//...

}

}

blog comments powered by Disqus