I was engaged in a discussion recently and the subject of software patterns came up. More specifically, the strategy pattern became a point of discussion. I have used this pattern before though I never placed a name to it. I find that several patterns seem to have multiple names and some are so close in functionality to others that it is not so clear which is which.
The strategy pattern is also known as the policy pattern. There you go again with the multiple names.
The strategy pattern is a means whereby the algorithm for some class action can be selected at run time. A class defines a method yet has a mechanism for selecting the algorithm for that method at run time. This can be implemented in many ways depending on the programming language in use.
Let’s say there is a class that calculates the total for an invoice. Let’s give this class a method that calculates tax. The tax calculation may be different depending on where the purchaser lives. We design the calculator class to have a tax calculator method. This method will call another method that lives in a tax calculator class. We allow the tax calculator class to be supplied to the calculator class at any time. We can then determine which tax calculator to use whenever we need to. Then we can instantiate the tax calculator and pass it to the calculator class which in turn uses it to calculate the tax among the other things it does.
According to Strategy pattern, the behaviors of a class should not be inherited, instead they should be encapsulated using interfaces.
Why is this a good thing?
We can redefine the tax calculator classes any time we want without touching any of the other classes in the system. This allows us to separate the algorithms and allow changes with zero possible impact on any other area of the system.
Similar patterns to consider:
Adapter
Driver/Plugin
Related Articles
No user responded in this post
Leave A Reply
Please Note: Comment moderation maybe active so there is no need to resubmit your comments