古典的Strategy模式
#pragma once
#include <functional>
class GameCharacter;
class HealthCalcFunc
{
public:
virtual int calc(const GameCharacter &gc) const;
~HealthCalcFunc() {}
};
class AnotherHealthCalcFunc : public HealthCalcFunc
{
public:
virtual int calc(const GameCharacter &gc) const;
};
class GameCharacter
{
public:
explicit GameCharacter(int val, HealthCalcFunc *phcf) : m_val(val), pHealthCalc(phcf) {}
int healthValue() const;
int getVal() const;
private:
int m_val;
HealthCalcFunc *pHealthCalc;
};
#include "func.h"
int HealthCalcFunc::calc(const GameCharacter &gc) const {
return gc.getVal();
}
int GameCharacter::healthValue() const {
return pHealthCalc->calc(*this);
}
int GameCharacter::getVal() const {
return m_val;
}
int AnotherHealthCalcFunc::calc(const GameCharacter &gc) const {
return 2 * gc.getVal();
}
#include <iostream>
#include "func.h"
int main() {
HealthCalcFunc fhc;
AnotherHealthCalcFunc shc;
GameCharacter gc1(2, &fhc);
GameCharacter gc2(2, &shc);
std::cout << gc1.healthValue() << std::endl;
std::cout << gc2.healthValue() << std::endl;
return 0;
}
std::function实现的Strategy模式
#include <iostream>
#include <functional>
class GameCharacter
{
public:
typedef std::function<int(const GameCharacter &)> HealthCalcFunc;
explicit GameCharacter(int val, HealthCalcFunc hcf) : m_val(val), m_healthFunc(hcf) {}
int healthValue() const {
return m_healthFunc(*this);
}
int getVal() const {
return m_val;
}
private:
int m_val;
HealthCalcFunc m_healthFunc;
};
short calcHealth(const GameCharacter & gc) {
return 2 * gc.getVal();
}
struct HealthFunctor
{
int operator()(const GameCharacter &gc) {
return 3 * gc.getVal();
}
};
int main() {
GameCharacter gc1(2, calcHealth);
GameCharacter gc2(2, &calcHealth);
GameCharacter gc3(2, HealthFunctor());
GameCharacter gc4(2, [](const GameCharacter &gc) {return 4 * gc.getVal(); });
std::cout << gc1.healthValue() << std::endl;
std::cout << gc2.healthValue() << std::endl;
std::cout << gc3.healthValue() << std::endl;
std::cout << gc4.healthValue() << std::endl;
return 0;
}