在通常的策略模式中,我们将每个策略作为一个类.我们不能使它成为一个函数,只是在我们实例化一个对象时分配对该函数的引用,并让该对象调用该函数吗?
在最简单的情况下,您可以用函数指针替换策略模式。但是,考虑一下这种情况
class HourlyPayStrategy implements PayStrategy
{
public int calculate()
{
int x = doComplexOperation1();
int y = doComplexOperation2();
return x + y;
}
private int doComplexOperation1()
{
// ...
}
private int doComplexOperation2()
{
// ...
}
}
Run Code Online (Sandbox Code Playgroud)
如果我们只给出一个简单的函数指针,事情就会开始变得非常棘手,因为你无法再重构那个东西(好吧,至少不能以良好封装的方式重构)。