Can you tell me any design pattern which you have used recently in your project, except Singleton? This is one of the popular question from various Java interviews in recent years. I think, this actually motivated many Java programmers to explore more design patterns and actually look at original 23 patterns introduced by GOF. Strategy pattern is one of the useful pattern you can mention while answering such question. It's very popular and there are lots of real world scenario where Strategy pattern is very handy. Many programmer ask me what is the best way to learn design pattern, I say you first need to find how other people use it and for that you need to look at the open source libraries you use in your daily task. JDK API is one such library I use on daily basis and that's why when I explore new algorithms, design pattern, I first search JDK for their usage. Strategy has found its place in JDK, and you know what I mean if you have sorted ArrayList in Java. Yes, combination of
Comparator,
Comparable and
Collections.sort() method are one of the best real world example of Strategy design pattern. To understand it more, let's first find out
what is Strategy pattern? First clue is in the name itself. The strategy pattern defines a family of related algorithms e.g. sorting algorithms like
bubble sort,
quicksort,
insertion sort and merge sort, or compression algorithm e.g. zip, gzip, tar, jar, encryption algorithm e.g. MD 5, AES etc and lets the algorithm vary independently from clients that use it. For example, you can use Strategy pattern to implement a method which sort numbers and allows client to choose any sorting algorithm at run time, without modifying client's code. So essentially Strategy pattern provides flexibility, extensible and choice. You should consider using this pattern when you need to select an algorithm at runtime. In Java, strategy is usually implemented by creating a hierarchy of classes that extend from a base interface known as Strategy. In this tutorial, we will learn some interesting things about Strategy pattern by writing a Java program and demonstrating how it add value to your code.