策略模式(Strategy)

来源:互联网 发布:mac给ios手机装 编辑:程序博客网 时间:2024/05/21 01:57

策略模式:它定义了算法家族,分别封装起来,让他们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的可会。[DP]
这里写图片描述

  1. 策略模式是一种定义一系列算法的方法,从概念上来看,所有这些算法完成的都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少了各种算法类与使用算法类之间的耦合[DPE]。
  2. 策略模式的Strategy类层次为Context定义了一系列的可供重用的算法或行为。继承有助于析取出这些算法中的公共功[DP]。
  3. 策略模式的优点简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试[DPE]。
  4. 策略模式是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中听到需要在不同时间引用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性[DPE]。
#include<iostream>using namespace std;class  Strategy{public:    virtual   void  AlgorithmInterface() = 0;};class  StrategyA :public Strategy{public:    virtual   void  AlgorithmInterface(){        cout << "策略A" << endl;    }};class  StrategyB :public Strategy{public:    virtual   void  AlgorithmInterface(){        cout << "策略B" << endl;    }};class  StrategyC :public Strategy{public:    virtual   void  AlgorithmInterface(){        cout << "策略C" << endl;    }};class  Context{private:    Strategy* strgy;public:    Context(){        this->strgy = nullptr;    }    // + 工厂模式  每当增加一种新策略的时候还需要在改switch    void selectsetStrategy(char c){        switch (c){        case 'A':            this->strgy =new StrategyA;            break;        case 'B':            this->strgy = new StrategyB;            break;        case 'C':            this->strgy = new StrategyC;            break;        }    }    void  ContextInterface(char c){        selectsetStrategy(c);        strgy->AlgorithmInterface();        delete  strgy;    }};int main(){     Context  context;    context.ContextInterface('B');    context.ContextInterface('C');    context.ContextInterface('A');    return 0;}
0 0
原创粉丝点击