September 30, 2011

Strategy Design Pattern code example in Java

The Abstract Type (the dependency)

public interface SortInterface {
   public void sort(List l);
}

The Concrete Implementations of the Abstract Type

public class QuickSort implements SortInterface {
   public void sort(List l) { ... }
}

public class BubbleSort implements SortInterface {
   public void sort(List l) { ... }
}

The Dependent Abstract Type

import SortInterface;

public abstract class Sorter {
   private SortInterface si;

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

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

   public void doSort(List listToSort);
}

The Dependent Concrete Type

public class MySorter extends Sorter {

   public void doSort(List listToSort) {
      getSorter().sort(listToSort);
      // other processing here
   }
}

The Client

import MySorter;
import BubbleSort;

public class Client {
   MySorter mysorter = new MySorter();

   mysorter.setSorter(new BubbleSort());
   mysorter.doSort();

   mysorter.setSorter(new QuickSort());
   mysorter.doSort();
}

No comments:

Post a Comment