Tuesday, 31 December 2013

Strategy Design pattern - Implementation [Sort]

Want to Master Java Design Patterns?

Subscribe to Ram N Java for clear, beginner-friendly coding examples!

Subscribe on YouTube

What Is the Strategy Design Pattern?

The Strategy Design Pattern is a behavioral design pattern that lets you define a family of algorithms, put each of them into a separate class, and make their objects interchangeable at runtime.

Instead of hardcoding a specific algorithm directly inside your business logic, the client chooses the required strategy dynamically based on requirements or user input.

Real-Time Scenario: Sorting an Array

Suppose you have an array of integers that needs to be sorted. You have multiple sorting algorithms available, such as:

  • Bubble Sort: Simple, but slower on large datasets.
  • Selection Sort: Better performance than Bubble Sort.
  • Insertion Sort: Faster and more efficient for small or partially sorted datasets.

Rather than writing multiple if-else or switch blocks in your main code, we encapsulate each sorting algorithm into its own strategy class.

Key Components of the Implementation

This pattern consists of three core elements:

  • Strategy Interface (SortingStrategy): Defines the common operation (e.g., sort(int[] array)) implemented by all sorting algorithms.
  • Concrete Strategies: Classes like BubbleSort, SelectionSort, and InsertionSort that provide specific implementations of the sorting logic.
  • Context (SortContext): Maintains a reference to one of the concrete strategies and delegates the sorting execution to it.

Java Implementation Overview

1. Define the Strategy Interface:

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

2. Configure the Context Class:

public class SortContext {
    private SortingStrategy sortingStrategy;

    public void setSortingStrategy(SortingStrategy sortingStrategy) {
        this.sortingStrategy = sortingStrategy;
    }

    public void sort(int[] numbers) {
        sortingStrategy.sort(numbers);
    }
}

3. Execute the Strategy at Runtime:

SortContext context = new SortContext();

// Select Bubble Sort or Insertion Sort dynamically
context.setSortingStrategy(new InsertionSort());
context.sort(inputArray);

Related Design Pattern Tutorials to Watch Next


Click here to watch in Youtube : https://www.youtube.com/watch?v=Ga-DD7HVhXU

Click the below Image to Enlarge
Strategy Design pattern - Implementation [Sort]


Strategy Design pattern - Implementation [Sort] - Class Diagram

































SortingStrategy.java

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

BubbleSort.java

public class BubbleSort implements SortingStrategy
{

public int[] sort( int[] inputArray )
{
int n = inputArray.length;
for( int i = 0; i < n; i++ )
{
for( int j = 1; j < (n - i); j++ )
{
if( inputArray[j - 1] > inputArray[j] )
{
swap(j - 1, j, inputArray);
}
}
}
System.out.println("Array is sorted using Bubble Sort Algorithm");
return inputArray;
}

private void swap( int k, int l, int[] inputArray )
{
int temp = inputArray[k];
inputArray[k] = inputArray[l];
inputArray[l] = temp;
}
}

InsertionSort.java

public class InsertionSort implements SortingStrategy
{

public int[] sort( int[] inputArray )
{

for( int i = 1; i < inputArray.length; i++ )
{
// a temporary copy of the current element
int tmp = inputArray[i];
int j;

// find the position for insertion
for( j = i; j > 0; j-- )
{
if( inputArray[j - 1] < tmp )
break;
// shift the sorted part to right
inputArray[j] = inputArray[j - 1];
}

// insert the current element
inputArray[j] = tmp;
}
System.out.println("Array is sorted using Insertion Sort Algorithm");
return inputArray;
}

}

SelectionSort.java

public class SelectionSort implements SortingStrategy
{

public int[] sort( int[] inputArray )
{

// find the smallest element starting from position i
   for (int i = 0; i < inputArray.length - 1; i++)
   {
       int min = i;  // record the position of the smallest
       for (int j = i + 1; j < inputArray.length; j++)
       {
           // update min when finding a smaller element
           if (inputArray[j] < inputArray[min])
               min = j;
       }

       // put the smallest element at position i
       swap(inputArray, i, min);
   }
System.out.println("Array is sorted using Selection Sort Algorithm");
return inputArray;
}

private void swap( int[] inputArray,int k, int l )
{
int temp = inputArray[k];
inputArray[k] = inputArray[l];
inputArray[l] = temp;
}
}


SortContext.java

import java.util.Scanner;

public class SortContext
{

private SortingStrategy sortingStrategy;

public void setSortingStrategy( SortingStrategy sortingStrategy )
{
this.sortingStrategy = sortingStrategy;
}

private void printArray( int[] inputArray )
{
for( int i = 0; i < inputArray.length; i++ )
{
System.out.print(inputArray[i] + ",");
}
System.out.println("\n");

}

private int[] readUserInput()
{
System.out.println("Enter array size : ");

Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();

System.out.println("Enter input array  : ");
int[] inputArray = new int[n];
for( int i = 0; i < n; i++ )
{
inputArray[i] = scanner.nextInt();
}
return inputArray;
}

public void sort()
{
int[] inputArray = readUserInput();
inputArray = sortingStrategy.sort(inputArray);
printArray(inputArray);
}
}

StrategyClient.java

import java.util.Scanner;

public class StrategyClient
{
public static void main( String[] args )
{

System.out.println("Please enter Sort Algorithm  : 'BubbleSort' or 'SelectionSort' or 'InsertionSort'");
Scanner scanner = new Scanner(System.in);
String sortAlgorithm = scanner.next();
System.out.println("Sort Algorithm is : " + sortAlgorithm);

SortContext context = new SortContext();


if( "BubbleSort".equalsIgnoreCase(sortAlgorithm) )
{
context.setSortingStrategy(new BubbleSort());
}
else if( "SelectionSort".equalsIgnoreCase(sortAlgorithm) )
{
context.setSortingStrategy(new SelectionSort());
}
else if( "InsertionSort".equalsIgnoreCase(sortAlgorithm) )
{
context.setSortingStrategy(new InsertionSort());
}

context.sort();

}
}

Output

Please enter Sort Algorithm  : 'BubbleSort' or 'SelectionSort' or 'InsertionSort'
BubbleSort
Sort Algorithm is : BubbleSort
Enter array size :
5
Enter input array  :
3 4 5 1 2
Array is sorted using Bubble Sort Algorithm
1,2,3,4,5,


Please enter Sort Algorithm  : 'BubbleSort' or 'SelectionSort' or 'InsertionSort'
InsertionSort
Sort Algorithm is : InsertionSort
Enter array size :
5
Enter input array  :
3 2 1 4 5
Array is sorted using Insertion Sort Algorithm
1,2,3,4,5,


See also:


  • Strategy Design pattern - Introduction
  • Strategy Design pattern - Real Time Example [Compress files]
  • Strategy Design pattern - Real Time Example [Payment]
  • Strategy Design pattern - Real Time Example [Travel]
  • Strategy Design pattern - Real Time Example [Sorting]
  • Strategy Design pattern - Real Time Example [Search]
  • Strategy Design pattern - Class Diagram
  • Strategy Design pattern - Sequence Diagram
  • Strategy Design pattern - Implementation [Compress files]
  • Strategy Design pattern - Implementation [Travel]
  • Strategy Design pattern - Implementation [Payment]
  • Strategy Design pattern - Implementation [Search]
  • Strategy Design pattern - KeyPoints
  • All Design Patterns Links
  • 1 comment:

    Tutorials