If you read my blog for a while, you have encountered the pattern already; perhaps without knowing it.
The strategy pattern comes at hand, if you extract concrete behaviour out of your class, making the class more generic/abstract in doing things. If you extract behaviour you are following another (good) principle, called »Open-Closed-Principle«. We see later, what is meant by this.
I’m referring to my somehow favourite expample: Logging in application; because i think, that this is a task, with whom every developer has to deal with. So look at the example above.
Instead of implementing three time a logging mechanism within my application, I encapsulated the task in an Interface called ILogging. So every time I am in need for logging i have to wire up my application with something, that is able to provide Logging. Whether it is a real full implemented Logger or just a mockup doesn’t matter for my application. I provided a gap, which could be filled with different Objects. That makes my application flexible in respect to not depending on any special kind of Logger and likewise is my application more testable: I could provide a mockup logger and test, whether my application behaves correct with the use-case of logging.
Another example for strategy would be a tax calculator engine, where taxes were calculated for different countries. Every country has a special set of taxes; so i could build a generic application, which makes use of the different set of taxes in a different calculation strategy.
So, why is this following the »Open-Closed-Principle«?
The Open-Closed-Principle -the 2nd of the SOLID Principles, which i am dealing with in another post- says something like the following: Your Object has to be open for extension and closed for modification. What does that mean?
If we look at our tax-engine: the tax-engine is in so far closed, as the behavior of calculating different taxes in different countries is encapsulated and is fix due the interfaces, which states some kind of behavioural contract, i.e. the interface defines explicit, what actions are required from a class, implementing it. Or you could say: an interface contains a set of rules for running the game. If another class wants to provide features of calculating taxes with my engine, it has to implement the interface (obey the rules set by that interface).
On the other hand: new rules do not require to rewrite/modificate the tax-engine: Only a new behavioural class has to be implemented, to provide new features for the tax-engine. And so it is open for extension.


