Thursday, November 10, 2011


Part 2: Strategy Pattern


It depends upon couple of general rule.

a) Identify the aspect of your application that vary and separate them from what stays the same.

b) Program to an Interface, not an implementation.

c) Prefer composition instead of Inheritance.

d) Open for extension close for the modification.

if you include all the above 3 rule in the design, it will become stategy pattern.
 - It defines a family of algorithm, encapsulates each one and make them interchangeable. Stategy let the algorithm vary independently from client that use it.

The below image is created using UMLet  tool.
Use strategy pattern when you have multiple ways of solving the same problem. Your application client interacts with a context that contains a strategy that implements its business functionality. The benefit is that you can easily add additional strategies (interface) that provide alternate functionality without disrupting your application’s processing enviroment.

Problem:
consider the example of having the sorting a string based on mergesort or quicksort, depending on the size of array. if the size of array is greater than 100 then use mergesort otherwise use quicksort.

now before start  we need to keep following below thing in mind.
1) what if later new sorting mechanism is required to sort

2) client  should not know any thing about the how the sorting operation done, he just need to call the abract  method for sort. instead of calling directly the sorting method.

3) consider all the above rule define at the start too.


class Sorting {

public static void main (String [ ] args) {

}

}

===========================================

Class ContextSorting {

SortingAction sa = null;
ArrayList al = new ArrayList();

contextSorting( SortingAction  s, ArrayList arr ) { 
  sa = s;
  al = arr; 
}
public setsortingAction (SortingAction  s){
sa  =s;
}

public void  callSort(){
  sa.sort(al)
}
}

==================================

Interface Sort {
public void sort (ArrayList al);
}

public MergeSort  implements Sort {
public void sort (ArrayList al) {
  mergesort (al);
}


public QuickSort  implements Sort {
public void sort (ArrayList al) {
  quicksort (al);
}


======================================================
Reference Material: