Strategy Pattern in Java

Started learning Design Patterns, recently. People suggested the books, “Head First Design Pattern” and “Gang of Four Book”. But I reached out for something simpler. I started with this YouTube playlist.

I should say, it was little bit confusing when I started. But eventually, it is all about minimizing the effort of maintenance, and reducing code duplication.

There are 3 different kind of Design Patterns.

Creational : How objects are created
Behavioral : How objects interact (behave) with each other
Structural : How objects are structured or laid out (relation with each other)

(If there was an E, we could have called it CBSE 😜 )

Strategy pattern belong to Behavioral Pattern.

Strategy pattern, is all about encapsulating strategies(algorithms).

Say for example, your project implements Binary Search. We all know that, for a binary search to work, the array should be sorted. For sorting arrays, we have multiple algorithms. You could use bubble sort for smaller array(<100), quick sort for medium sized array (<2500), or may be parallelSort() for large arrays (≥2500). Strategy used for each type of array(based on array length), is different.

Small, Medium, Large 😵

As per strategy pattern, instead of hard coding the sorting algorithm, we could encapsulate the strategy to different classes (using interface), and use it dynamically based on the array length. Reminded me of the quote:

If all you have is a hammer, everything looks like a nail

Never mind 😅

Concrete classes are Noun. Algorithms are adjectives.

  1. Will start with the Noun. (Duck in the Head First Design Patterns book)

2. We find adjectives, and create Interface and Concretions for the algorithms.

Adjectives ( Fly, NoFly, RocketFly for Ducks)

3. Finally the Driver Program to Test.

Found it Interesting?
Please show your support by 👏. To read the complete series, click below.

I myself, has just started learning, design patterns. If you find any issues please feel free to post them in the comments section below. Thank you for reading so far 😄

Writes on Big Data, AWS & Backend technologies.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store