A Developer's Diary

Nov 23, 2012

Strategy Design Pattern

Strategy Pattern
The strategy pattern allows you to use different business rules or algorithms depending on the context in which they occur

When should I use the Strategy Pattern?
1. You can perform an operation in different ways
2. You want to select the operation dynamically at the runtime
3. You want to add new ways without modifying the application code

Real World Examples
1. File Compression Techniques
2. Layout Managers used by Containers in Java Swing
3. Comparators used in Arrays sort function

Below is a simple application which makes use of the strategy pattern to select the type of algorithm to use for sorting
1. The Driver Program
package patterns.example.strategy;

import patterns.example.strategy.ApplicationRunner.Sort;

/**
 * 
 * File: StrategyExample.java
 */
public class StrategyExample
{
    public static void main(String[] args) {
        ApplicationRunner.init();
        ApplicationRunner.getOrderedEmployees(Sort.INSERTION);
    }
}

2. The Application Runner Program
A simulation of application program which loads employees and returns an ordered list of employees
package patterns.example.strategy;

import java.util.ArrayList;
import java.util.List;

/**
 * 
 * File: ApplicationRunner.java
 */
public class ApplicationRunner
{
    private static List<String> employees = null;

    public enum Sort {
        INSERTION,
        SELECTION
    };

    public static void init() {
        employees = new ArrayList<String>();
        employees.add("Zach");
        employees.add("Albie");
        employees.add("Brynne");
        employees.add("Elf");
        employees.add("Fiona");
        employees.add("Prince");
        employees.add("James");
        employees.add("Hitman");
    }

    public static List<String> getOrderedEmployees(Sort type) {
        Sorter sorter = new Sorter();
        sorter.setSortStrategy(SortFactory.getSortStrategy(type));
        sorter.sort(employees);
        return employees;
    }

    static class SortFactory
    {
        public static SortStrategy getSortStrategy(Sort type) {
            switch (type)
            {
                case INSERTION:
                    return new InsertionSortStrategy();
                case SELECTION:
                    return new SelectionSortStrategy();
                default:
                    return new SelectionSortStrategy();
            }
        }
    }
}

3. Sorter Program. The program by default uses Selection Sort as the default sorting algorithm if none is specified
package patterns.example.strategy;

import java.util.List;

/**
 * 
 * File: Sorter.java
 */

public class Sorter
{
    private SortStrategy sortStrategy = new SelectionSortStrategy();

    public Sorter() {}

    public void setSortStrategy(SortStrategy sortStrategy) {
        this.sortStrategy = sortStrategy;
    }

    public void sort(List<String> names) {
        this.sortStrategy.sort(names);
    }
}

4. The SortStrategy Interface
package patterns.example.strategy;

import java.util.List;

/**
 * 
 * File: SortStrategy.java
 */
public interface SortStrategy
{
    public <T extends Comparable<T>> void sort(List<T> elems);
}

5. The SelectionSortStrategy implementation
package patterns.example.strategy;

import java.util.List;

/**
 * 
 * File: SelectionSortStrategy.java
 */
public class SelectionSortStrategy implements SortStrategy
{
    @Override
    public <T extends Comparable<T>> void sort(List<T> elems) {
        for (int outerLoopIdx = 0; outerLoopIdx < elems.size() - 1; ++outerLoopIdx) {
            int min = outerLoopIdx;
            for (int innerLoopIdx = outerLoopIdx; innerLoopIdx < elems.size(); ++innerLoopIdx) {
                if (elems.get(min).compareTo(elems.get(innerLoopIdx)) > 0) {
                    min = innerLoopIdx;
                }
            }
            exchange(elems, min, outerLoopIdx);
        }
    }

    private <T extends Comparable<T>> void exchange(List<T> elems, int lhs, int rhs) {
        T temp = elems.get(lhs);
        elems.set(lhs, elems.get(rhs));
        elems.set(rhs, temp);
    }
}

6. The InsertionSortStrategy implementation
package patterns.example.strategy;

import java.util.List;

/**
 * 
 * File: InsertionSortStrategy.java
 */

public class InsertionSortStrategy implements SortStrategy
{
    @Override
    public <T extends Comparable<T>> void sort(List<T> elems) {
        for (int outerLoopIdx = 1; outerLoopIdx < elems.size(); ++outerLoopIdx) {
            for (int innerLoopIdx = outerLoopIdx; innerLoopIdx > 0; --innerLoopIdx) {
                if (elems.get(innerLoopIdx - 1).compareTo(elems.get(innerLoopIdx)) > 0) {
                    T temp = elems.get(innerLoopIdx - 1);
                    elems.set(innerLoopIdx - 1, elems.get(innerLoopIdx));
                    elems.set(innerLoopIdx, temp);
                }
            }
        }
    }
}

References:
Strategy Pattern
Code Project Tutorial

1 comment :

Unknown said...

interesting blog. It would be great if you can provide more details about it. Thanks you









Java Training Courses

Post a Comment