C++设计模式3————(策略模式)

来源:互联网 发布:八爪鱼软件 编辑:程序博客网 时间:2024/06/03 22:00

策略模式

1.概述

策略模式是将算法的不同实现封装到一个类里面,将算法的实现和算法的使用分离。在算法发生变化时不会影响算法的调用者。在需要不同算法时,可以相互替换,而不影响使用者。
下面是UML图:

2.C++代码实现:

以下是策略基类和子类:
#ifndef BASESTRATEGYINTERFACE_H#define BASESTRATEGYINTERFACE_Hclass BaseStrategyInterface{public:    BaseStrategyInterface();public:    virtual void AlgorithmFunction()=0;};#endif // BASESTRATEGYINTERFACE_H
<pre name="code" class="cpp">#ifndef STRATEGYA_H#define STRATEGYA_H#include "basestrategyinterface.h"class StrategyA : public BaseStrategyInterface{public:    StrategyA();public:    void AlgorithmFunction();};#endif // STRATEGYA_H#include "strategya.h"#include <iostream>using namespace std;StrategyA::StrategyA(){}void StrategyA::AlgorithmFunction(){    cout << "Strategy A" << endl;}
<pre name="code" class="cpp">#ifndef STRATEGYB_H#define STRATEGYB_H#include "basestrategyinterface.h"class StrategyB : public BaseStrategyInterface{public:    StrategyB();public:    void AlgorithmFunction();};#endif // STRATEGYB_H#include "strategyb.h"#include <iostream>using namespace std;StrategyB::StrategyB(){}void StrategyB::AlgorithmFunction(){    cout << "Strategy B" << endl;}
<pre name="code" class="cpp">#ifndef STRATEGYC_H#define STRATEGYC_H#include "basestrategyinterface.h"class StrategyC : public BaseStrategyInterface{public:    StrategyC();public:    void AlgorithmFunction();};#endif // STRATEGYC_H#include "strategyc.h"#include <iostream>using namespace std;StrategyC::StrategyC(){}void StrategyC::AlgorithmFunction(){    cout << "Strategy C" << endl;}


#ifndef REPLACE_H#define REPLACE_H#include "basestrategyinterface.h"#include <iostream>class Replace{private:    BaseStrategyInterface *m_Instance;public:    Replace(BaseStrategyInterface *strategy)    {        m_Instance = strategy;    }    ~Replace()    {        if(m_Instance != NULL)        {            delete m_Instance;        }    }public:    void Algorithm()    {        m_Instance->AlgorithmFunction();    }};#endif // REPLACE_H
调用策略方法:
Replace *replaceA = new Replace(new StrategyA());replaceA->Algorithm();delete replaceA;Replace *replaceB = new Replace(new StrategyB());replaceB->Algorithm();delete replaceB;Replace *replaceC = new Replace(new StrategyC());replaceC->Algorithm();delete replaceC;
输出:

Strategy A

Strategy B

Strategy C

以上是策略模式的最简单实现方式,也可以使用其他实现方式,其根本思想不变。

0 0