Strategy Design Pattern

Strategy: This is an interface to describe the individual algorithms.

public interface SortInterface {
    public void sort(double[] list);
}

ConcreteStrategy: Implements Strategy Interface and contains the logic for the algorithm.

public class QuickSort implements SortInterface {
    public void sort(double[] a) {
        //implementation
    }
}
public class BubbleSort implements SortInterface {
    public void sort(double[] a) {
        //implementation
    }
}

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 SortingContext(SortInterface sorter) {
        this.sorter = sorter;
    }
    public void sortDouble(double[] list) {
        sorter.sort(list);
    }
 
    public SortInterface getSorter() {
        return sorter;
    }
 
}

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.

public class SortingClient {
    public static void main(String[] args) {
        double[] list = {1,2.4,7.9,3.2,1.2,0.2,10.2,22.5,19.6,14,12,16,17};
        SortingContext context = new SortingContext(new BubbleSort());
        context.sortDouble(list);
        for(int i =0; i< list.length; i++) {
            System.out.println(list[i]);
        }
    }
}
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License