Strategy Design Pattern (Java)

Vibhor Pareek
2 min readFeb 16, 2021

--

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:

  1. Merge Sort Strategy
Concrete Class 1

2. Quick Sort Strategy

Concrete Class 2

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 :

Context Class

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

Client Call

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

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Vibhor Pareek
Vibhor Pareek

No responses yet

Write a response