In the usual Strategy Pattern, we make each strategy as a class. Can't we make it a function, and just assign the reference to the function when we instantiate an object, and let the object call that function?
views:
191answers:
5Depends on the language. In C#, you could make it a delegate. In Java, it would rather be a anonymous class. In C++, you could really make it a function pointer.
Sure, although by using objects you can take advantage of inheritance in ways that you couldn't with just functions.
In the simplest cases, you can replace Strategy patterns with a function pointer. However, consider this case
class HourlyPayStrategy implements PayStrategy
{
public int calculate()
{
int x = doComplexOperation1();
int y = doComplexOperation2();
return x + y;
}
private int doComplexOperation1()
{
// ...
}
private int doComplexOperation2()
{
// ...
}
}
If we just gave a simple function pointer, things start getting really hairy because you can no longer refactor that thing (well, at least not in an well encapsulated way).
What happens below the hood in most C++ implementations is almost what you suggest. The compiler usually resolves a call Strategy.virtualMethod() like this (in pseudo code):
(Strategy.pVtable[indexOfVirtualMethod])()
So if your only concern is the one more dereferencing of a pointer (pVtable) you should really profile first if you cannot identify more serious hotspots.
My feeling is that your code will be much harder to understand and maintain when you use a function pointer instead of a strategy object.