Strategy Pattern — get the gist in 2 min.
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!