C++ Strategy pattern

John Humphreys - w00te picture John Humphreys - w00te · Sep 6, 2011 · Viewed 9.9k times · Source

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 :)

Answer

fredoverflow picture fredoverflow · Sep 6, 2011

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.