Strategy Pattern — get the gist in 2 min.

aditya chaudhari
JavaDeveloperDiary — JDD
2 min readJun 21, 2022
strategy pattern —get the gist of it in 1 minute.

All intent behind the strategy pattern is to encapsulate behaviors that belongs to a similar purpose and make them interchangeable .
Behaviors are methods in OO design and here encapsulation means creating different strategy classes which have dedicated logic that can be interchanged by other logic (even on runtime) to solve a similar category purpose.

When you have a situation where you have to write different methods which belong to a similar cause but each of those has different logic to solve that problem then think about using a strategy pattern.

Simple Example
1. You have a multicountry eCommerce webstore where different countries have different 3rd party API to get the shipping cost for the respective country.
But you have the same cart which holds this price, it’s just by the country you want to choose which 3rd party API you want to call, and get a respective shipping price.
Think of using a strategy pattern in such cases. — [github_code_link] .

Structure and different components in strategy pattern.
As you can see in the diagram above there are 4 important components in any strategy pattern .

Client Class : helps associate strategy with context class
Context Class : which holds reference to concrete strategies
Strategy Interface : Interface common to all concrete strategies
Concrete Strategies : Implementation, which is actually different variations of the algorithms used by the context.

The real fun is in the details, if you wish to know and understand different styles of strategy pattern and java code examples, pros-cons, please consider visiting my detailed article at [strategy-pattern-java-explained-6-min-read]

Thanks for reading. Love IT, Live IT, Enjoy IT.

Every Tuesday I am writing an exciting technical article, please consider following if you wish to get notified!

--

--

aditya chaudhari
JavaDeveloperDiary — JDD

building efficient, scalable and maintainable enterprise e-commerce applications using java, spring framework and SAP CC. Life Mantra → Love IT Live IT Enjoy IT