由function pointers和std::function完成的strategy模式;
class GameCharacter;
int defaultHealthCalc(const GameCharacter& gc){return 1;};
int loseHealthQuickly(const GameCharacter& gc){ cout<<“loseHealthQuickly”<<endl; return 2;};
int loseHealthSlowly(const GameCharacter& gc){ cout<<“loseHealthSlowly”<<endl; return 3;};
short calcHealth(const GameCharacter&) {return 4;};
class GameCharacter {
public:
//如下两个typedef的区别在于,第一个调用时一个必须是此类型的函数指针;
//第二个是可以进行转型的
//typedef int (*HealthCalcFunc)(const GameCharacter&);
typedef std::function<int (const GameCharacter&)> HealthCalcFunc;
explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc)
: healthFunc(hcf)
{ cout<<“base constructor”<<endl;}
GameCharacter()
{
cout<<"default base constructor"<<endl;
}
int healthValue() const
{ return healthFunc(*this); }
private:
HealthCalcFunc healthFunc;
};
class EvilBadGuy: public GameCharacter {
public:
explicit EvilBadGuy(HealthCalcFunc hcf = defaultHealthCalc)
: GameCharacter(hcf) //Attention: 当该函数参数没有默认参数时:explicit EvilBadGuy(HealthCalcFunc hcf),除非显示调用父类的带参构造函数,否则默认调用的是父类的default构造函数或者无参的构造函数,如果父类只提供带参构造函数,编译器则不会自动提供default构造函数,这时编译就会报错
{cout<<“child constructor”<<endl;}
};
int main()
{
EvilBadGuy ebg1(loseHealthQuickly); //用
EvilBadGuy ebg2(loseHealthSlowly);
EvilBadGuy ebg3(calcHealth); //在typedef int (*HealthCalcFunc)(const GameCharacter&);是会报错的,只能用可转型的typedef
return 0;
}
古典的Strategy模式:
class GameCharacter;
class HealthCalcFunc {
public:
virtual int calc(const GameCharacter& gc) const
{}
}
class GameCharacter {
public:
explicit GameCharacter(HealthCalcFunc *hcf)
: pHealthFunc(hcf)
{ cout<<“base constructor”<<endl;}
GameCharacter()
{
cout<<"default base constructor"<<endl;
}
int healthValue() const
{ return hcf->calc(*this); }
private:
HealthCalcFunc* pHealthFunc;
};