Pages

Thursday, 15 October 2015

Strategy Pattern

Strategy Pattern (Policy Pattern) - The behavioral design pattern

Strategy pattern is used when we have multiple algorithm for a specific task and client decides the actual implementation to be used at runtime.
We defines multiple algorithms/classes and let client application pass the algorithm to be used as a parameter.

Example: Collections.sort() method that takes Comparator parameter. The list can be sorted in different ways using different implementations of Comparator interfaces.
                       

Elements Strategy Pattern

Strategy  (SortStrategy)
Common Interface that implemented by to all supported algorithms (ConcreteStrategy).

ConcreteStrategy  (QuickSort, ShellSort, MergeSort)
Implements the algorithm using the Strategy interface.

Context  (SortedList)
Maintains a reference to a Strategy object and logic to use Strategy object.

package strategy;

interface Strategy {
      public void sort(int[] numbers);
}

class BubbleSort implements Strategy {
      @Override public void sort(int[] numbers) {
            System.out.println("Buuble sort !!");
      }
}

class InsertionSort implements Strategy {
      @Override public void sort(int[] numbers) {
            System.out.println("Insertion sort !!");
      }
}

class QuickSort implements Strategy {
      @Override public void sort(int[] numbers) {
            System.out.println("Quick sort !!");
      }
}

class MergeSort implements Strategy {
      @Override public void sort(int[] numbers) {
            System.out.println("Merge sort !!");
      }
}

class Context {
      private final Strategy strategy;
      public Context(Strategy strategy) {
            this.strategy = strategy;
      }
      public void arrange(int[] input) {
            strategy.sort(input);
      }
}

public class StrategyTest {
      public static void main(String args[]) throws InterruptedException {

            int[] var = {1, 2, 3, 4, 5};
           
            /** Define Bubble sort to at run time. */
            Context ctx = new Context(new BubbleSort());
            ctx.arrange(var); // we can change the strategy without changing Context class
           
            /** Define Quick sort to at run time. */
            ctx = new Context(new QuickSort());
            ctx.arrange(var);
      }
}
Output:
      Buuble sort !!
      Quick sort !!

No comments:

Post a Comment