Wednesday, April 2, 2008

Startegy pattern

Simple way. You have list of objects, you need to perform a function on them. The way you perform the function may differ. For eg sorting a list. You can use diff sorting strategies. You dont want to couple a strategy of sorting with the list.

First interface,

  • Strategy: This is an interface to describe the individual algorithms.
    public interface SortInterface {
    public void sort(double[] list);
    }
    SortInterface.java
  • ConcreteStrategy: Implements Strategy Interface and contains the logic for the algorithm.
    public class QuickSort implements SortInterface {
    public void sort(double[] a) {
    quicksort(a, 0, a.length - 1);
    }
    private void quicksort(double[] a, int left, int right) {
    if (right <= left) return;
    int i = partition(a, left, right);
    quicksort(a, left, i-1);
    quicksort(a, i+1, right);
    }

    private int partition(double[] a, int left, int right) {
    int i = left;
    int j = right;
    while (true) {
    while (a[i]< a[right])
    i++;
    while (less(a[right], a[--j]))
    if (j == left) break;
    if (i >= j) break;
    exch(a, i, j);
    }
    exch(a, i, right);
    return i;
    }

    private boolean less(double x, double y) {
    return (x < y);
    }

    private void exch(double[] a, int i, int j) {
    double swap = a[i];
    a[i] = a[j];
    a[j] = swap;
    }
    }
    QuickSort.java
    public class BubbleSort implements SortInterface {
    public void sort(double[] list) {
    double temp;
    for(int i = 0; i < list.length; i++) {
    for(int j = 0; j < list.length - i; j++) {
    if(list[i] < list[j]) {
    temp = list[i];
    list[i] = list[j];
    list[j] = temp;
    }
    }
    }
    }
    }
    BubbleSort.java
  • Context: The context maintains a reference to a Strategy object and forwards client requests to the strategy. Context may also define an interface to let Strategies access context data.
    public class SortingContext {
    private SortInterface sorter = null;

    public void sortDouble(double[] list) {
    sorter.sort(list);
    }

    public SortInterface getSorter() {
    return sorter;
    }

    public void setSorter(SortInterface sorter) {
    this.sorter = sorter;
    }
    }
    SortingContext.java
  • Client: The client sets the concrete strategy in the context and invokes the context to run the algorithm. You can also have the context set the Concrete strategy implementation itself, based on the request.
    public class SortingClient {
    public class SortingClient {
    public static void main(String[] args) {
    double[] list = {1,2.4,7.9,3.2,1.2,0.2,10.2,22.5,19.6,14,12,16,17};
    SortingContext context = new SortingContext();
    context.setSorter(new BubbleSort());
    context.sortDouble(list);
    for(int i =0; i< list.length; i++) {
    System.out.println(list[i]);
    }
    }
    }
    SortingClient.java

No comments: