Thursday, March 15, 2012

The Strategy pattern

This is one of the more simple patterns and is really useful. It is ideal for encapsulating rules and simplifying those if-else or switch statements.

If you have some code that looks at an object and makes a decision based on a property of the object, then you may need to consider the Strategy. You should also consider this if you think that you may, at some point, get asked to add another clause into that switch statement. Maybe the code calculates the exchange rate for US$, and Euro. But what happens when the Business decides they want the British £ also.
For that you may need to add an else clause or extend the Switch.

That's not good really as it breaks the Open-Closed principle. I have a post on this which contains a code example.

This diagram gives a general idea of the pattern.

As an example we could have an object that needs to calculate the exchange rate. So, at construction time we could inject the required calculator and the object calls the relevant method. If we want to add another currency calculator, say UKPound, then we create the new class UKPoundCalculator, it implements the interface IExchangeRateStrategy, and we pass it to the contact class. The beauty is, there are no changes made to the CalculateTheCost context class.

Open-Closed Principle

No comments:

Post a Comment