Strategy Design Pattern (Java)
Behavioural Design Pattern in Java
Introduction
Strategy pattern is a behavioural design pattern which helps you to decide on choosing type of algorithm from a set of algorithms during runtime. Java Collections.sort() method uses strategy pattern to determine what type of comparator to be passed during runtime and acts accordingly. Hope this has given little bit of insight on strategy pattern.
Where can we apply Strategy Pattern
This is one of the most asked questions in an interview to a senior developer/tech lead/architect while doing a low level design problem. Answer is pretty straightforward, you have a set of predefined algorithms to choose which can be encapsulated in a new class/implementation, allowing the caller/client to decide on what algorithm to use at runtime.
Code Walkthrough
Let’s take a simple example of sorting numbers with different strategies. We are now creating an interface defining sort function.

Interface defining Strategy
Let’s try to implement concrete classes defining different strategies:
- Merge Sort Strategy

2. Quick Sort Strategy

Ah! pretty simple, now how do client call and decide runtime behaviour for the class ? Let’s create a context class and set the context determining your implementation as follows :

We have now reached the end of implementation, let’s try calling it and see :)

Hope you have understood the usage of Strategy Pattern :) Keep Learning !