In the past, I have seen the strategy pattern explained as a mechanism which allows the user of a function/class to provide their own functionality for that function/class.
I had always been taught that the way to implement the pattern was by taking function pointers into your classes/functions and calling them internally, thus allowing the programmer to provide their own "strategy" which would be used internally by those functions and objects.
Looking around more recently, I see that the strategy pattern always seems to be explained/defined through the use of an inheritance hierarchy like so:
Strategy pattern implementation
is this a difference of opinion/implementation, or is the function pointer passing not really a variation of the strategy pattern? I'm mostly interested so I don't confuse people when I comment or explain my code :)
Design Patterns in the object-oriented world is a reusable solution to common software design problems that occur repeatedly in real-world application development. It is a template or description of how to solve problems that can be used in many situations. "A pattern is a recurring solution to a problem in a context."
As a Plan, strategy needs to be developed in advance and with purpose. As a Ploy, strategy is a means of outsmarting the competition. With strategy as a Pattern, we learn to appreciate that what was successful in the past can lead to success in the future.
Solution. The Strategy pattern suggests that you take a class that does something specific in a lot of different ways and extract all of these algorithms into separate classes called strategies. The original class, called context, must have a field for storing a reference to one of the strategies.
Use the Strategy pattern when you want to use different variants of an algorithm within an object and be able to switch from one algorithm to another during runtime. Use the Strategy when you have a lot of similar classes that only differ in the way they execute some behavior.
You simply have to use inheritance in languages without function pointers (read: Java).
Personally, I would prefer std::function
over raw function pointers, because it accepts a wider range of arguments and allows you to maintain state in the strategy object.
Also, if you already know the strategy at compile-time, you can even use templates and thus save both the space and runtime overhead of function pointers and std::function
objects.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With