Monday, December 11, 2006

Implementing Strategy Pattern in Java

The previous post described the Strategy pattern in brief. I listed out where and why the strategy pattern may be used. This post describes how to implement command pattern in Java and also some implementation considerations. This example here uses sorting algorithms. Two sorting algorithms (Bubble sort and Quick sort) are implemented and the client can select either the algorithms. Here is the UML diagram for the Strategy Pattern.The following is a simple description of each of the elements of the above diagram, followed by a simple implementation.

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.

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.