您的位置:首页 > 编程语言 > C语言/C++

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

2014-12-04 13:39 225 查看

策略模式

1.概述

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



2.C++代码实现:

以下是策略基类和子类:
#ifndef BASESTRATEGYINTERFACE_H
#define BASESTRATEGYINTERFACE_H

class 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
以上是策略模式的最简单实现方式,也可以使用其他实现方式,其根本思想不变。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: