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.
Pre-requisite:
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.
Nutshell:
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.
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 😅
Project structure
Implementation in Java
Concrete classes are Noun. Algorithms are adjectives.
- Will start with the Noun. (Duck in the Head First Design Patterns book)
BinarySearch.java
2. We find adjectives, and create Interface and Concretions for the algorithms.
ISorter.java
Adjectives ( Fly, NoFly, RocketFly for Ducks)
SmallSorter.java
MediumSorter.java
LargerSorter.java
3. Finally the Driver Program to Test.
StrategyDriver.java
Found it Interesting?
Please show your support by 👏. To read the complete series, click below.
Reference:
Disclaimer:
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 😄