Strategy Pattern

2015/09/03

Strategy Pattern

Strategy Pattern enables an algorithm’s behavior to be selected at runtime. It provides a way to define a family of algorithms, encapsulate each one as an object (one strategy), and make them interchangeable to carry out some specific behavior.

Think about now you want to go out, you can choose to take a bus or call a Taxi, you could even take a bus firstly and then change to a bike. The Strategy Pattern is to be used for this situation where you want to choose the algorithm/strategy to use at run-time.

In fact, we could choose if else to realize this. But this will cause the following problems:

  • Every time you add a new strategy, you need to change the code on client side. So adda new else.
  • Many “If … else …” in your code cause maintenance to be difficult.

So Strategy Pattern is here to help you add and choose an algorithm/strategy.

When Use Strategy Pattern

1, If your system in which there are many classes, the only difference between them is their behaviors, then use the strategy pattern can be dynamically allows to choose a behavior.

2, If your system needs to dynamically select one of several algorithms.

Structure

Strategy Pattern

  • Strategy defines an interface for all supported strategy. Context uses this interface to call the strategy defined by a ConcreteStrategy.

  • ConcreteStrategy is each concrete strategy simple implementing Strategy interface.

  • Context has a reference of Strategy. It separates strategy itself and its duty (How it should be used). Client will use Context to add/change one Strategy. And Client can swap ConcreteStrategys in and out without effecting our Context.

For more details, Context receives requests from the client and delegates them to the strategy object. Usually ConcreteStartegy is created by the client and passed to Context. From this point the clients interacts only with Context. So a new strategy can not effect that much on Client. A Client only needs to know those Strategies already existing.

Exemple

Now we want to sort something. There are three strategys to choose:

  • Bubble Sort
  • Insertion Sort
  • Selection Sort
public interface Sort{
    public abstract int[] sort(int arr[]);
}

public class BubbleSort implements Sort{
    public int[] sort(int arr[]){
        // Bubble Sort
        return arr;
    }
}

public class InsertionSort implements Sort {
    public int[] sort(int arr[]) {
        // Insertion Sort
        return arr;
    }
}

public class SelectionSort implements Sort {
    public int[] sort(int arr[]) {
        // Selection Sort
        return arr;
    }
}

Context:

public class Handler
{
    private Sort sortObj;

    public int[] sort(int arr[])
    {
        sortObj.sort(arr);
        return arr;
    }

    public void setSortObj(Sort sortObj) {
        this.sortObj = sortObj;
    }
}

Client to test:

public class Client {

    public static void main(String args[]) {

        int arr[] = {1,4,6,2,5,3,7,10,9};
        int result[];
        Handler handler = new Handler();

        // Choose strategy selectionSort
        handler.setSortObj(new SelectionSort());
        result=ah.sort(arr);

        for(int i=0;i<result.length;i++) {
            System.out.print(result[i] + ",");
        }

        // Choose strategy insertionSort
        handler.setSortObj(new InsertionSort());
        result=ah.sort(arr);

        for(int i=0;i<result.length;i++) {
            System.out.print(result[i] + ",");
        }
    }
}

Ref

Post Directory