Strategy Pattern

Badri Narayanan Sugavanam
2 min readJul 13, 2021

The most fundamental building blocks for a developer are the design patterns. By following a design pattern, we mould the software to have specific advantages and uses.

When writing software, we always would have come with the problem of supporting multiple types of an object and choosing an object’s behaviour at runtime. The above issues are perfect candidates for using strategy pattern.

Lets us examine a hypothetical problem to solve:

We have an application called MyBrandedSearch which currently have two types of search partners

SearchPartnerOne and SearchPartnerTwo

The SearchApplication MyBrandedSearchEngine should be able to switch SearchPartners based on the type/behaviour.The behaviour is set at runtime.

The old way to achieve this is to use switch case or any conditional like below.

We could achieve the same by using a cleaner strategy pattern. Here we encapsulate all the behaviours in separate Interfaces and concrete classes. The logic is on those concrete classes. If we add another type/behaviour we add a new interface, and thus changes are not in the existing classes.

Class Diagram StrategyPattern for MyBrandedSearch
public class MyApplication {
public static void main(String[] args) {
SearchEngine myBrandedSearch = new MyBrandedSearch();
myBrandedSearch.setSearchBehaviour(new SearchPartnerOneConcrete());
myBrandedSearch.performSearch();
myBrandedSearch.setSearchBehaviour(new SearchPartnerTwoConcrete());
myBrandedSearch.performSearch();
}
}

In above the behaviours can be switched by SearchPartnerOneConcrete() or SearchPartnerTwoConcrete().

The complete code can be found in the github at https://github.com/badri-mel/java-design-patterns/tree/main/StrategyPattern.

--

--