方法1:利用多态实现策略模式
#include <iostream>
using namespace std;
class Strategy
{
public:
virtual void fun() = 0;
};
class StrategyA : public Strategy
{
public:
virtual void fun()
{
cout << "StrategyA" << endl;
}
};
class StrategyB : public Strategy
{
public:
virtual void fun()
{
cout << "StrategyB" << endl;
}
};
class Context
{
public:
//注意:抽象类不能实例化,所以声明为引用。可以将子类对象传递给抽象类引用。
Context(Strategy &strtgy)
{
this->strtgy = &strtgy;
}
void operation()
{
strtgy->fun();
}
private:
Strategy *strtgy;
};
void main()
{
StrategyA strtgy1;
Context cntxt1(strtgy1);
cntxt1.operation();
StrategyB strtgy2;
Context cntxt2(strtgy2);
cntxt2.operation();
system("pause");
}
程序运行结果:
方法2:利用类模板实现策略模式
#include <iostream>
using namespace std;
class StrategyA
{
public:
void fun()
{
cout << "StrategyA" << endl;
}
};
class StrategyB
{
public:
void fun()
{
cout << "StrategyB" << endl;
}
};
template<class Strategy>
class Context
{
public:
void operation()
{
strtgy.fun();
}
private:
Strategy strtgy;
};
void main()
{
Context<StrategyA> cntxt1;
cntxt1.operation();
Context<StrategyB> cntxt2;
cntxt2.operation();
system("pause");
}
程序运行结果: