Let’s first try to understand what a strategy is. In simple worlds a strategy is a plan (for something). Or a little more elaboration “a plan, method, or series of maneuvers or stratagems for obtaining a specific goal or result”.
For purpose of understanding, let’s take a simple example. Say we want to create a piece of code to calculate the tax for a given salary. An added complexity is that code should work for multiple countries. All these countries will have different strategy (formula) for tax calculation. Based on the country provided as input, we will need to change our strategy for tax calculation at the run time.
So how does strategy pattern help us? Let’s solve the above mentioned problem with tax calculation to make it clear.
The above image makes it clear. We have 2 strategies to calculate tax, one for India and other for Germany. While initializing the strategy pattern class object(TaxCalculator), we will define which strategy is to be followed.
TaxCalculator taxCalculator(new IndiaTaxStrategy());
taxCalculator.calculateMyTax();//calculateMyTax will simply call the parent class calculate tax method with the income