Want to Master Java Design Patterns?
Subscribe to Ram N Java for clean code examples and beginner-friendly guides!
Subscribe on YouTubeUnderstanding 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
LinearSearchandBinarySearchimplementing 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
| 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
No comments:
Post a Comment