设计模式-策略模式

shienh 2020年01月23日 165次浏览

策略(Strategy)模式的定义:该模式定义了一系列算法,并将每个算法封装起来,使它们可以相互替换,且算法的变化不会影响使用算法的客户。策略模式属于对象行为模式,它通过对算法进行封装,把使用算法的责任和算法的实现分割开来,并委派给不同的对象对这些算法进行管理。

#include <iostream>
using namespace std;

//抽象武器策略
class WeaponStrategy{
public:
    virtual void UseWeapon()=0;

};

class Knife:public WeaponStrategy{
public:
    virtual void UseWeapon(){
        cout<<"use knife"<<endl;
    }
};

class Ak47:public WeaponStrategy{
public:
    virtual void UseWeapon(){
        cout<<"use Ak47"<<endl;
    }
};

class Character{
public:
    void setWeapon(WeaponStrategy* weapon){
        this->pWeapon = weapon;
    }

    void ThrowWeapon(){
        this->pWeapon->UseWeapon();
    }
public:
    WeaponStrategy* pWeapon;
};

int main(int argc, char *argv[])
{
    Character* character = new Character;
    WeaponStrategy* knife = new Knife;
    WeaponStrategy* ak47 = new Ak47;
    character->setWeapon(knife);
    character->ThrowWeapon();

    character->setWeapon(ak47);
    character->ThrowWeapon();
    delete knife;
    delete ak47;
    delete  character;
    return 0;
}