【设计模式】之二十三种设计模式--策略模式

策略模式

Define a family of algorithms,encapsulate each one,and make them interchangeable.
(定义一组算法,将每个算法都封装起来,并且使它们之间可以互换。)

通用类图

封装类,承上启下,屏蔽高层模块对策略、算法的直接访问。与抽象策略类是聚合关系
抽象策略类,策略、算法的抽象,定义必须具有的方法和属性
具体策略类,实现抽象的操作,含有具体的方法,继承抽象策略类

通用源码

//抽象策略类
class Strategy {
public:
    //策略模式的运算法则
    virtual void doSomething() = 0;
};
//具体策略类
class ConcreteStrategy1 : public Strategy {
public:
    virtual void doSomething() {
        //具体策略1的运算法则
    }
};
class ConcreteStrategy2 : public Strategy {
public:
    virtual void doSomething() {
        //具体策略2的运算法则
    }
};
//封装类
class Context {
private:
    Strategy* strategy = NULL;
public:
    Context(Strategy *s): strategy(s) { }
    void doAnything() {
        strategy->doSomething();
    }
};

优点

算法可以自由切换
避免使用多重条件判断
扩展性良好

缺点

策略类数量增多
所有的策略类都需要对外暴露

使用场景

多个类只有在算法或行为上稍有不同的场景
算法需要自由切换的场景
需要屏蔽算法规则的场景

示例代码

#include <iostream>

using namespace std;

class IStrategy {
public:
    virtual void operate() = 0;
};

class BackDoor : public IStrategy {
public:
    virtual void operate() {
        cout << "find helper, add pressure" << endl;
    }
};

class GivenGreenLight : public IStrategy {
public:
    virtual void operate() {
        cout << "open green light, let out" << endl;
    }
};

class BlockEnemy : public IStrategy {
public:
    virtual void operate() {
        cout << "lady Sun in back" << endl;
    }
};

class Context {
private:
    IStrategy *strategy = NULL;
public:
    Context(IStrategy *is): strategy(is) { }
    void operate() {
        strategy->operate();
    }
};

int main() {
    Context *context = NULL;
    context = new Context(new BackDoor());
    context->operate();
    context = new Context(new GivenGreenLight());
    context->operate();
    context = new Context(new BlockEnemy());
    context->operate();
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值