# Strategy Design Pattern

The Strategy pattern is a behavioral pattern that allows you to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. This pattern is useful when you have a set of related algorithms that can be used interchangeably, or when you want to provide different ways to accomplish a task.

In the following example, we will create a strategy for sorting an array of integers:

``````import java.util.Arrays;

public interface SortingStrategy {
void sort(int[] arr);
}

public class BubbleSort implements SortingStrategy {
public void sort(int[] arr) {
int n = arr.length;
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
}

public class QuickSort implements SortingStrategy {
public void sort(int[] arr) {
quickSort(arr, 0, arr.length-1);
}

private void quickSort(int[] arr, int low, int high) {
if (low < high) {
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot-1);
quickSort(arr, pivot+1, high);
}
}

private int partition(int[] arr, int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j <= high-1; j++) {
if (arr[j] < pivot) {
i++;
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
}

public class ArraySorter {
private SortingStrategy strategy;

public void setStrategy(SortingStrategy strategy) {
this.strategy = strategy;
}

public void sort(int[] arr) {
strategy.sort(arr);
}
}

public class Main {
public static void main(String[] args) {
int[] arr = {5, 3, 7, 1, 8, 4, 2, 9, 6};
ArraySorter sorter = new ArraySorter();
sorter.setStrategy(new BubbleSort());
sorter.sort(arr);
System.out.println(Arrays.toString(arr));

sorter.setStrategy(new QuickSort());
sorter.sort(arr);
System.out.println(Arrays.toString(arr));
}
}``````

In this example, we have a SortingStrategy interface that defines a sort() method for sorting an array of integers. We also have two classes that implement the SortingStrategy interface: BubbleSort and QuickSort. BubbleSort implements the bubble sort algorithm, and QuickSort implements the quicksort algorithm.

We also have an ArraySorter class that has a SortingStrategy instance variable and a setStrategy() method for setting the sorting strategy. The ArraySorter class also has a sort() method that delegates the sorting to the SortingStrategy object.

In the main() method, we create an array of integers and an ArraySorter object. We then set the ArraySorter’s sorting strategy to BubbleSort and sort the array, outputting the sorted array using the Arrays.toString() method. We then set the sorting strategy to QuickSort and sort the array again, outputting the sorted array

Technology
Companies:
Amdocs Siemens
Topics:
Type:
theory
Contributed by: