Saturday, October 20, 2007

Strategy vs Observer








Strategy
Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it.


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

My Comments:
  • For strategy pattern, since we don't want to change the SortedList class in the future, we need to abstract the three sort classes, so we have the SortStrategy abstract class, we just need to include the SortStrategy as a local variable in the SortedList class
  • For observer pattern, since we don't want to change the Stock class in the future, we need to abstract the Investor classes, so we have the IInvestor interface, we just need to include the IInvestor as a local variable in the Stock class
  • So from above, these two patterns are the same, they all implement the open-close principle
  • The difference lies in the definition.
  • The SortedList is a concrete class, it can swap sorting at run time, but only choose one sorting at a time
  • The Stock is an abstract class, it can add/remove Investors at run time, and notify all the Inverstors when the stock price changes
  • So that's the difference

blog comments powered by Disqus