Strategy-object Behavioral

古典的Strategy模式
#pragma once

#include <functional>

class GameCharacter;  // forward declaration

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值