Sunday, December 12, 2010

Design Patterns - An eye for similarities - Part 2

The Strategy Pattern - Divide and Rule

WHAT IS STRATEGY PATTERN?
The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.[Taken from Wikipedia]

HOW DOES IT WORK?
In essence, all the strategy pattern says is to identify the things in the application that can change (verbs) in the application and separate it from the things that don't (nouns).
Generalize the verbs into a family of interfaces and create encapsulations for each of them which form the concrete classes.
E.g: [ From the book - Head First Design Patterns]



The Observer Pattern - Tell me, I'll let you know

WHAT IS OBSERVER PATTERN?
The observer pattern defines a one to many dependency between objects so that when one object changes state, all of it's dependents are notified and updated automatically.

HOW DOES IT WORK?
The Observer Pattern consists of a publisher that publishes events and subscribers that subscribe to that event. Thus, in effect, it helps makes the system loosely coupled by providing an interface for 2 objects to talk without actually having to maintain any relationship.
For example in a shopping application the stock manager and the sales manager would have subscribed to the event on the click of the "BUY" button on an inventory. Thus the cart might fire an event saying that a particular inventory has been bought. The sales and the stock manager having subscribed to the event get notifications to process the information furthur.

Related:
Part 3 [Decorator Pattern]
Part 4 [ Factory Pattern ]

No comments :