Friday, May 27, 2016

Strategy Design Pattern tutorial example java

What is Strategy Design Pattern?

Strategy pattern is used when we want different algorithms needs to be applied  on objects.This pattern where algorithms can be selected at runtime.Strategy pattern is also known as the "Policy Pattern" .

For Example:

A mode of transportation to an airport is an example of this pattern because you have multiple options  such as driving your own car,by taxi,b bus etc.

When to use Strategy Pattern:

we can apply Strategy pattern when we need different variants of an algorithm and these related classes differ only in their behavior.


Implementation:

/**
 * @author Abhinaw.Tripathi
 *
 */

interface SortInterface {
public void sort(int[] array);
}

class QuickSort implements SortInterface {

@Override
public void sort(int[] array) {
// TODO Auto-generated method stub
// do quick sort logic here
}

}

class BubbleSort implements SortInterface {

@Override
public void sort(int[] array) {
// TODO Auto-generated method stub
// do Bubble sort logic
}

}

abstract class Sorter {

private SortInterface strategy;

public void setSorter(SortInterface strtegy) {
this.strategy = strtegy;
}

public SortInterface getSorter() {
return this.strategy;
}

abstract void doSort(int[] listToSort);
}

class MySorter extends Sorter {

@Override
void doSort(int[] listToSort) {
// TODO Auto-generated method stub
getSorter().sort(listToSort);
// other things to do
}

}

public class StrategyTest {

/**
*
*/
public StrategyTest() {
// TODO Auto-generated constructor stub
}

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

int[] listToBeSorted = { 18, 26, 26, 12, 127, 47, 62, 82, 3, 236, 84, 5 };
MySorter mySorter = new MySorter();
mySorter.setSorter(new BubbleSort());
mySorter.doSort(listToBeSorted);
mySorter.setSorter(new QuickSort());
mySorter.doSort(listToBeSorted);

}

}

No comments: