Showing posts with label Strategy Pattern. Show all posts
Showing posts with label Strategy Pattern. Show all posts

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
  • Monday, 30 December 2013

    Strategy Design pattern - Implementation [Search]

    Want to Master Java Design Patterns?

    Subscribe to Ram N Java for clean code examples and beginner-friendly guides!

    Subscribe on YouTube

    Understanding Search Algorithms with Strategy Pattern

    When building applications that search through data, different situations require different search techniques. Instead of coupling your search logic tightly inside a single class, the Strategy Design Pattern enables you to swap search algorithms cleanly at runtime.

    In this guide, we explore how to encapsulate search logic such as Linear Search and Binary Search into independent strategy classes.

    Why Use Strategy Pattern for Search?

    Consider these typical search scenarios in Java:

    • Linear Search: Scans element by element. Perfect for small collections or unsorted datasets.
    • Binary Search: Much faster with logarithmic time complexity, but strictly requires sorted data.

    By applying the Strategy Pattern, your client code does not need complex if-else conditions. You can simply assign whichever search strategy fits the state of your data.

    Core Components of the Implementation

    • Strategy Interface (SearchStrategy): Declares the search method signature common to all search algorithms.
    • Concrete Strategies: Classes like LinearSearch and BinarySearch implementing the strategy interface.
    • Context (SearchContext): Holds a reference to the active strategy and executes the search request.

    Java Code Walkthrough

    1. Define the Common Search Strategy Interface:

    public interface SearchStrategy {
        public int search(int[] numbers, int target);
    }

    2. Build the Context Class:

    public class SearchContext {
        private SearchStrategy searchStrategy;
    
        public void setSearchStrategy(SearchStrategy searchStrategy) {
            this.searchStrategy = searchStrategy;
        }
    
        public int executeSearch(int[] numbers, int target) {
            return searchStrategy.search(numbers, target);
        }
    }

    3. Choose and Execute Strategy at Runtime:

    SearchContext context = new SearchContext();
    
    // Use Binary Search for sorted datasets
    context.setSearchStrategy(new BinarySearch());
    int resultIndex = context.executeSearch(sortedArray, 45);

    Related Design Pattern Tutorials to Watch Next



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

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


    Strategy Design pattern - Implementation [Search] - Class Diagram

































    SearchStrategy.java

    public interface SearchStrategy
    {
    int search(int[] list, int elementToSearch);
    }

    BinarySearch.java

    public class BinarySearch implements SearchStrategy
    {

    @Override
            public int search( int[] list, int elementToSearch )
            {

               int position = 0;

               for (int i = 0; i < list.length; i++)
               {
                   if (list[i] == elementToSearch)
                   {
                       position = i;
                       break;
                   }
               }
           
               System.out.println("Position of the element has been found using BinarySearch Algorithm");
           
               return position;
            }


    }

    LinearSearch.java

    public class LinearSearch implements SearchStrategy
    {

    @Override
    public int search( int[] list, int elementToSearch )
    {
    int beg = 0;
    int end = list.length - 1;
    int mid = (int) ((beg + end) / 2);
    int position = 0;

    while( beg <= end && list[mid] != elementToSearch )
    {
    if( elementToSearch < list[mid] )
    end = mid - 1;
    else
    beg = mid + 1;

    mid = (int) ((beg + end) / 2);
    }

    if( list[mid] == elementToSearch )
    position = mid;
    else
    position = 0;

    System.out.println("Position of the element has been found using LinearSearch Algorithm");

    return position;
    }

    }

    SearchContext.java

    public class SearchContext
    {

    private SearchStrategy searchStrategy;

    public void setSearchStrategy( SearchStrategy searchStrategy )
    {
    this.searchStrategy = searchStrategy;
    }

    public int search( int[] list, int item )
    {
    return searchStrategy.search(list, item);
    }
    }


    StrategyClient.java

    import java.util.Scanner;

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

    System.out.println("Please enter Search Algorithm  : 'Linear' or 'Binary'");
    Scanner scanner = new Scanner(System.in);
    String searchAlgorithm = scanner.next();
    System.out.println("Search Algorithm is : " + searchAlgorithm);

    System.out.println("\nPlease enter element to be searched : ");
    Scanner scanner1 = new Scanner(System.in);
    int elementToSearch = scanner1.nextInt();
    System.out.println("ElementToSearch is : " + elementToSearch);

    SearchContext context = new SearchContext();


    if( "Linear".equalsIgnoreCase(searchAlgorithm) )
    {
    context.setSearchStrategy(new LinearSearch());
    }
    else if( "Binary".equalsIgnoreCase(searchAlgorithm) )
    {
    context.setSearchStrategy(new BinarySearch());
    }

    int[] sortedList = { 1, 2, 3, 4, 5, 6, 7, 8 };

    int position = context.search(sortedList,elementToSearch);

    System.out.println("Position of the element is : "+ position);

    }
    }

    Output

    Please enter Search Algorithm  : 'Linear' or 'Binary'
    Linear
    Search Algorithm is : Linear

    Please enter element to be searched :
    5
    ElementToSearch is : 5
    Position of the element has been found using LinearSearch Algorithm
    Position of the element is : 4


    Please enter Search Algorithm  : 'Linear' or 'Binary'
    Binary
    Search Algorithm is : Binary

    Please enter element to be searched : 
    7
    ElementToSearch is : 7
    Position of the element has been found using BinarySearch Algorithm
    Position of the element is : 6

    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 [Sort]
  • Strategy Design pattern - KeyPoints
  • All Design Patterns Links
  • Strategy Design pattern - Implementation [Payment]

    Want to Master Java Design Patterns?

    Subscribe to Ram N Java for clean code walkthroughs and real-world architectures!

    Subscribe on YouTube

    Why Use Strategy Pattern in Payment Processing?

    E-commerce and billing systems require support for diverse payment methods such as Credit Card, PayPal, and UPI / Net Banking.

    Instead of writing messy if-else or switch blocks within a shopping cart or checkout service, the Strategy Design Pattern enables you to encapsulate each payment gateway into its own dedicated class.

    Key Advantages of This Approach

    • Open/Closed Principle: Add new payment modes (e.g., Apple Pay, Crypto) without modifying existing checkout code.
    • Loose Coupling: The checkout component does not care how individual payments are authorized.
    • Runtime Flexibility: Customers can freely change their payment choice right at checkout.

    Core Architecture Elements

    • PaymentStrategy (Interface): Declares the common method signature (e.g., pay(int amount)).
    • Concrete Strategies: Implementation classes such as CreditCardStrategy and PaypalStrategy.
    • ShoppingCart / PaymentContext: Maintains a reference to the selected PaymentStrategy and initiates payment processing.

    Java Code Implementation

    1. Define the Strategy Interface:

    public interface PaymentStrategy {
        public void pay(int amount);
    }

    2. Create Concrete Implementations:

    public class CreditCardStrategy implements PaymentStrategy {
        private String cardNumber;
    
        public CreditCardStrategy(String cardNumber) {
            this.cardNumber = cardNumber;
        }
    
        @Override
        public void pay(int amount) {
            System.out.println("Paid " + amount + " using Credit Card.");
        }
    }

    3. Configure the Context:

    public class ShoppingCart {
        private PaymentStrategy paymentStrategy;
    
        public void setPaymentStrategy(PaymentStrategy paymentStrategy) {
            this.paymentStrategy = paymentStrategy;
        }
    
        public void checkout(int amount) {
            paymentStrategy.pay(amount);
        }
    }

    Related Design Pattern Tutorials to Watch Next


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

    Click the below Image to Enlarge
    Strategy Design pattern - Implementation [Payment]
    Strategy Design pattern - Implementation [Payment] - Class Diagram




































    PaymentStrategy.java

    public interface PaymentStrategy
    {
    public void pay(String amount);

    }


    DebitCardPaymentStrategy.java

    public class DebitCardPaymentStrategy implements PaymentStrategy
    {

    public void pay(String amount)
    {
    System.out.println("Customer pays the money " +amount+ "Rs. using Debit Card");
    }

    }

    CreditCardPaymentStrategy.java

    public class CreditCardPaymentStrategy implements PaymentStrategy
    {

    public void pay( String amount )
    {
    System.out.println("Customer pays the money " + amount + "Rs. using Credit Card");
    }

    }

    ByCashPaymentStrategy.java

    public class ByCashPaymentStrategy implements PaymentStrategy
    {

    public void pay( String amount )
    {
    System.out.println("Customer pays the money " + amount + "Rs. as a Cash");
    }

    }


    PaymentContext.java

    public class PaymentContext
    {
    private PaymentStrategy paymentStrategy;

    // Client will set what PaymentStrategy to use by calling this method
    public void setPaymentStrategy(PaymentStrategy strategy)
    {
    this.paymentStrategy = strategy;
    }

    public PaymentStrategy getPaymentStrategy()
    {
    return paymentStrategy;
    }

    public void pay(String amount)
    {
    paymentStrategy.pay(amount);
    }

    }


    Customer.java

    import java.util.Scanner;

    public class Customer
    {

    public static void main( String[] args )
    {

    System.out.println("Please enter Payment Type : 'CreditCard' or 'DebitCard' or 'ByCash'");
    Scanner scanner = new Scanner(System.in);
    String paymentType = scanner.next();
    System.out.println("Payment type is : " + paymentType);

    System.out.println("\nPlease enter Amount to Pay : ");
    Scanner scanner1 = new Scanner(System.in);
    String amount = scanner1.next();
    System.out.println("amount is : " + amount);

    PaymentContext ctx = null;
    ctx = new PaymentContext();

    if( "CreditCard".equalsIgnoreCase(paymentType) )
    {
    ctx.setPaymentStrategy(new CreditCardPaymentStrategy());
    }
    else if( "DebitCard".equalsIgnoreCase(paymentType) )
    {
    ctx.setPaymentStrategy(new DebitCardPaymentStrategy());
    }
    else if( "ByCash".equalsIgnoreCase(paymentType) )
    {
    ctx.setPaymentStrategy(new ByCashPaymentStrategy());
    }

    System.out.println("PaymentContext has :"+ctx.getPaymentStrategy());

    ctx.pay(amount);

    }
    }

    Output

    Please enter Payment Type : 'CreditCard' or 'DebitCard' or 'ByCash'
    CreditCard
    Payment type is : CreditCard

    Please enter Amount to Pay :
    90000
    amount is : 90000
    PaymentContext has :CreditCardPaymentStrategy@1e4cbc4
    Customer pays the money 90000Rs. using Credit Card


    Please enter Payment Type : 'CreditCard' or 'DebitCard' or 'ByCash'
    DebitCard
    Payment type is : DebitCard

    Please enter Amount to Pay :
    90000
    amount is : 90000
    PaymentContext has :DebitCardPaymentStrategy@1e4cbc4
    Customer pays the money 90000Rs. using Debit Card


    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 [Search]
  • Strategy Design pattern - Implementation [Sort]
  • Strategy Design pattern - KeyPoints
  • All Design Patterns Links
  • Saturday, 28 December 2013

    Strategy Design pattern - Implementation [Travel]

    Want to Master Java Design Patterns?

    Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!

    Subscribe on YouTube

    Real-World Scenario: Choosing a Travel Mode

    When planning a trip, a traveler can reach their destination using different modes of transportation: Car, Bus, Train, or Flight. Each option has its own cost, travel duration, and route logic.

    In software design, modeling this with hardcoded conditions creates rigid, messy code. By applying the Strategy Design Pattern, each travel option becomes an interchangeable strategy class that can be switched dynamically at runtime.

    Why Use the Strategy Pattern Here?

    • Extensibility: Need to add bike or ferry travel later? Add a new class without modifying existing travel logic.
    • Clean Code: Eliminates complicated switch-case or conditional branches inside your booking engine.
    • Runtime Selection: Users can change their travel preference dynamically based on budget or schedule.

    Components of the Architecture

    • TravelStrategy (Interface): Declares common methods like travel(String source, String destination).
    • Concrete Strategies: Classes such as CarTravelStrategy, BusTravelStrategy, or FlightTravelStrategy.
    • Traveler / Context: Holds a reference to the selected TravelStrategy and executes the journey.

    Java Code Walkthrough

    1. Define the Common Strategy Interface:

    public interface TravelStrategy {
        void gotoAirport(String source, String destination);
    }

    2. Implement Concrete Strategies:

    public class TaxiTravelStrategy implements TravelStrategy {
        @Override
        public void gotoAirport(String source, String destination) {
            System.out.println("Traveling from " + source + " to " + destination + " by Taxi.");
        }
    }

    3. Build the Travel Context:

    public class TravelContext {
        private TravelStrategy travelStrategy;
    
        public void setTravelStrategy(TravelStrategy travelStrategy) {
            this.travelStrategy = travelStrategy;
        }
    
        public void travel(String source, String destination) {
            travelStrategy.gotoAirport(source, destination);
        }
    }

    Related Design Pattern Tutorials to Watch Next



    Click here to watch in Youtube : https://www.youtube.com/watch?v=37zZUuAuk7w

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



    Strategy Design pattern - Implementation [Travel] - Class Diagram



































    TravelStrategy.java

    public interface TravelStrategy
    {
    public void gotoAirport();
    }

    AutoTravelStrategy.java

    public class AutoTravelStrategy implements TravelStrategy
    {

    public void gotoAirport()
    {
    System.out.println("Traveler is going to Airport by Auto and will be charged 600 Rs");
    }

    }

    BusTravelStrategy.java

    public class BusTravelStrategy implements TravelStrategy
    {

    public void gotoAirport()
    {
    System.out.println("Traveler is going to Airport by bus and will be charged 200 Rs");
    }

    }

    TaxiTravelStrategy.java

    public class TaxiTravelStrategy implements TravelStrategy
    {

    public void gotoAirport()
    {
    System.out.println("Traveler is going to Airport by Taxi and will be charged 1000 Rs");
    }

    }


    TrainTravelStrategy.java

    public class TrainTravelStrategy implements TravelStrategy
    {

    public void gotoAirport()
    {
    System.out.println("Traveler is going to Airport by Train and will be charged 300 Rs");
    }

    }


    TravelContext.java

    public class TravelContext
    {
    private TravelStrategy travelStrategy;

    // Client will set what TravelStrategy to use by calling this method
    public void setTravelStrategy(TravelStrategy strategy)
    {
    this.travelStrategy = strategy;
    }

    public TravelStrategy getTravelStrategy()
    {
    return travelStrategy;
    }

    public void gotoAirport()
    {
    travelStrategy.gotoAirport();
    }

    }


    Traveler.java

    import java.util.Scanner;

    public class Traveler
    {

    public static void main( String[] args )
    {

    System.out.println("Please enter Travel Type : 'Bus' or 'Train' or 'Taxi' or 'Auto' ");
    Scanner scanner = new Scanner(System.in);
    String travelType = scanner.next();
    System.out.println("Travel type is : " + travelType);

    TravelContext ctx = null;
    ctx = new TravelContext();

    if( "Bus".equalsIgnoreCase(travelType) )
    {
    ctx.setTravelStrategy(new BusTravelStrategy());
    }
    else if("Train".equalsIgnoreCase(travelType))
    {
    ctx.setTravelStrategy(new TrainTravelStrategy());
    }
    else if("Taxi".equalsIgnoreCase(travelType))
    {
    ctx.setTravelStrategy(new TaxiTravelStrategy());
    }
    else if("Auto".equalsIgnoreCase(travelType))
    {
    ctx.setTravelStrategy(new AutoTravelStrategy());
    }
    System.out.println("Travel context has : "+ctx.getTravelStrategy());
    ctx.gotoAirport();

    }
    }


    Output

    Please enter Travel Type : 'Bus' or 'Train' or 'Taxi' or 'Auto'
    bus
    Travel type is : bus
    Travel context has : BusTravelStrategy@1e4cbc4
    Traveler is going to Airport by bus and will be charged 200 Rs


    Please enter Travel Type : 'Bus' or 'Train' or 'Taxi' or 'Auto' 
    train
    Travel type is : train
    Travel context has : TrainTravelStrategy@578ceb
    Traveler is going to Airport by Train and will be charged 300 Rs

    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 [Payment]
  • Strategy Design pattern - Implementation [Search]
  • Strategy Design pattern - Implementation [Sort]
  • Strategy Design pattern - KeyPoints
  • All Design Patterns Links
  • Friday, 27 December 2013

    Strategy Design pattern - Real Time Example [Search]

    Want to Master Java Design Patterns?

    Subscribe to Ram N Java for clean code, architecture patterns, and practical Java tutorials!

    Subscribe on YouTube

    Real-Time Search Problem in Software Design

    Searching is one of the most fundamental operations in software applications. Depending on how your data is structured, you might need a different search algorithm:

    • Linear Search: Ideal when the list of elements is completely unsorted or relatively small.
    • Binary Search: Extremely fast with logarithmic time complexity, but strictly requires the elements to be sorted beforehand.

    Instead of tying your search operation directly into a rigid class with nested conditional checks, the Strategy Design Pattern lets you extract these algorithms into interchangeable classes.

    How the Strategy Pattern Fits Search Algorithms

    The Strategy pattern defines a family of algorithms, encapsulates each algorithm into its own class, and makes them interchangeable from the client’s perspective:

    • Strategy Interface: Declares the contract (e.g., search(int[] list, int target)) that all search strategies must implement.
    • Concrete Strategies: Classes representing specific algorithms such as LinearSearchStrategy and BinarySearchStrategy.
    • Context: Maintains a reference to the active strategy object and executes the search dynamically at runtime.

    Why This Design Is Beginner-Friendly & Extensible

    When you decouple the search logic from the calling application:

    • Open/Closed Principle: You can easily introduce newer algorithms (such as Interpolation Search or Jump Search) without touching existing code.
    • Maintainability: Bug fixes or performance improvements in one algorithm do not break or affect any others.
    • Dynamic Swapping: Your program can inspect the dataset and automatically pick the fastest algorithm at runtime.

    Related Design Pattern Tutorials to Watch Next


    Click here to watch in Youtube : https://www.youtube.com/watch?v=5g7uGKXpFAw

    Click the below Image to Enlarge
    Strategy Design pattern - Real Time Example [Search]


















    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 - 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 - Implementation [Sort]
  • Strategy Design pattern - KeyPoints
  • All Design Patterns Links
  • Tutorials