参考:参考1
策略模式定义多种处理同一种场景的不同算法,这些算法可在不影响用户的情况下互相替换。
环境类(Context):持有一个具体的策略类的引用,提供给客户端调用。抽象策略类(Strategy):策略的抽象,一般定义接口。具体策略类(ConcreteStrategy):具体的策略实现,实现抽象策略类的接口。 2. 代码实现
- 抽象策略类,一般用于定义接口
class abs_stratege{
virtual void a()=0;//实现方法接口
}
- 具体策略类
class stra_A:public abs_stratege
{
void a()
{
//具体实现方法;
}
}
3.环境类
class evironment
{
public:
evironment(abs_stratege*stra){
e_stra=stra;
}
~evironment()
{
delete e_stra;
}
void start()
{
e_stra->a();
}
private:
abs_stratege*e_stra
}
3 代码实例
strategy.h
#pragma once #include#include using namespace std; class abs_str { public: virtual void method() = 0; }; class str_a :public abs_str { public: str_a() { std::cout << "这是A方法" << endl; } void method() { cout << "A方法在使用" << endl; } }; class str_b :public abs_str { public: str_b() { std::cout << "这是B方法" << endl; } void method() { cout << "B方法在使用" << endl; } }; class environment { private: abs_str *e_str; public: environment(abs_str *str) { e_str = str; } void use() { this->e_str->method(); } };
主程序
#include"strategy.h" #include#include using namespace std; int main() { environment evri(new str_a()); evri.use(); environment evri_1(new str_b()); evri_1.use(); return 0; }
运行截图:
相比于使用大量的if…else,使用策略模式可以降低复杂度,使得代码更容易维护。
缺点:
可能需要定义大量的策略类,并且这些策略类都要提供给客户端。客户端在短时间内只能使用一种策略。 5 工厂模式与策略模式的区别
工厂模式中只管生产实例,具体怎么使用工厂实例由调用方决定,策略模式是将生成实例的使用策略放在策略类中配置后才提供调用方使用。
工厂模式调用方可以直接调用工厂实例的方法属性等,策略模式不能直接调用实例的方法属性,需要在策略类中封装策略后调用。
参考:区别



