什么是策略模式:
借用HeadFirst中的定义,策略模式定义了算法族,分别封装起来,让他们之间可以相互替换,此模式让算法的变化独立于使用算法的客户
上代码
strategy.h
// strategy
#ifndef STRATEGY_H
#define STRATEGY_H
#include <iostream>
using namespace std;
class CAbstractStrategy
{
public:
virtual void strategy() = 0;
};
class CStrategy1 : public CAbstractStrategy
{
public:
virtual void strategy()
{
cout << "strategy1" << endl;
}
};
class CStrategy2 : public CAbstractStrategy
{
public:
virtual void strategy()
{
cout << "strategy2" << endl;
}
};
class CStrategy3 : public CAbstractStrategy
{
public:
virtual void strategy()
{
cout << "strategy3" << endl;
}
};
#endif //STRATEGY_H
content.h
#ifndef CONTENT_H
#define CONTENT_H
#include "strategy.h"
class CAbstractContent
{
public:
void UseStrategy()
{
m_strategy->strategy();
}
virtual void SetStrategy(CAbstractStrategy *pStrategy) = 0;
CAbstractStrategy *m_strategy;
};
class CContent1 : public CAbstractContent
{
public:
CContent1()
{
m_strategy = new CStrategy1;
}
virtual void SetStrategy(CAbstractStrategy *pStrategy)
{
m_strategy = pStrategy;
}
};
#endif //CONTENT_H
tt.cpp
#include <iostream>
#include "content.h"
#include "strategy.h"
using namespace std;
int main(int ac, char **av)
{
CContent1 content;
content.UseStrategy();
CAbstractStrategy *pStrategy2 = new CStrategy2;
CAbstractStrategy *pStrategy3 = new CStrategy3;
content.SetStrategy(pStrategy2);
content.UseStrategy();
content.SetStrategy(pStrategy3);
content.UseStrategy();
delete pStrategy2;
delete pStrategy3;
pStrategy2 = NULL;
pStrategy3 = NULL;
system("pause");
return 0;
}
运行结果
strategy1
strategy2
strategy3