C++设计模式——策略模式

策略模式(Strategy):它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的用户

Strategt类,定义所有支持的算法的公共接口

class Strategy {
public:
    virtual ~Strategy() {};
    virtual void AlgorithmInterface() = 0;
};

ConcreteStrategy 封装了具体的算法或行为,继承Strategy

class ConcreteStrategyA : public Strategy{
    void AlgorithmInterface() {
        cout << "算法A实现" << endl;
    }
};

class ConcreteStrategyB : public Strategy {
    void AlgorithmInterface() {
        cout << "算法B实现" << endl;
    }
};

class ConcreteStrategyC : public Strategy {
    void AlgorithmInterface() {
        cout << "算法C实现" << endl;
    }
};

Context,用一个ConcreteStrategy来配置,维护一个对Strategy的引用

class Context {
public:
    Context(Strategy* strategy) : m_strategy(strategy) {};
    ~Context() { free_ptr(m_strategy); }
    void AlgorithmInterface() {
        m_strategy->AlgorithmInterface();
    };
private:
    Strategy* m_strategy;
};

 

整份代码:

#include <algorithm>
#include <iostream>
using namespace std;
#define free_ptr(p) if(p) delete p; p = nullptr;

//Strategt类,定义所有支持的算法的公共接口
class Strategy {
public:
    virtual ~Strategy() {};
    virtual void AlgorithmInterface() = 0;
};

//ConcreteStrategy 封装了具体的算法或行为,继承Strategy
class ConcreteStrategyA : public Strategy{
    void AlgorithmInterface() {
        cout << "算法A实现" << endl;
    }
};

class ConcreteStrategyB : public Strategy {
    void AlgorithmInterface() {
        cout << "算法B实现" << endl;
    }
};

class ConcreteStrategyC : public Strategy {
    void AlgorithmInterface() {
        cout << "算法C实现" << endl;
    }
};

//Context,用一个ConcreteStrategy来配置,维护一个对Strategy的引用
class Context {
public:
    Context(Strategy* strategy) : m_strategy(strategy) {};
    ~Context() { free_ptr(m_strategy); }
    void AlgorithmInterface() {
        m_strategy->AlgorithmInterface();
    };
private:
    Strategy* m_strategy;
};


int main() {
    Strategy* concreteStrategyA = new ConcreteStrategyA();
    Strategy* concreteStrategyB = new ConcreteStrategyB();
    Strategy* concreteStrategyC = new ConcreteStrategyC();

    concreteStrategyA->AlgorithmInterface();
    concreteStrategyB->AlgorithmInterface();
    concreteStrategyC->AlgorithmInterface();

    free_ptr(concreteStrategyA);
    free_ptr(concreteStrategyB);
    free_ptr(concreteStrategyC);
    return 0;
}

 

优点:

1.策略模式的Strategy类层次为Context定义了一系列可供重用的算法或行为。继承有助于析取处这些算法中的公共功能...

2.策略模式的优点简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试

3.策略模式封装了变化

缺点:

1.用户必须知道所有的策列类

2.类过多-策略模式会造成很多的策略类,每个具体策略类都会产生一个新类

——参考大话设计模式

posted @ 2022-02-14 17:23  冰糖葫芦很乖  阅读(512)  评论(0编辑  收藏  举报