设计模式之策略模式

来源:互联网 发布:java资源下载网 编辑:程序博客网 时间:2024/04/30 03:52

1、策略模式定义了算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。结构图如下:




2、策略模式剖析:

策略模式是一种定义一系列算法的方法,从概念上看,所有这些算法完成都是相同的工作,只是实现不同,它可以以相同的方式调用所有的算法,减少各种算法类与使用算法类之间的耦合。

策略模式的Strategy类层次为Context定义了一系列可供重用的算法或行为。继承有助于抽象出这些算法的公共功能。

3、策略模式的优点是简化了单元测试,因为每个算法都有自己的类,可以通过自己的接口单独测试。

当不同的行为堆砌在一个类中时,就很难避免使用条件语句来选择适合的行为。将这些行为封装在一个个独立的Strategy类中,可以在使用这些行为的类中消除条件语句。


4、策略模式就是用来封装算法的,但在实践中,我们发现可以用它来封装几乎任何类型的规则,只要在分析过程中得到说需要在不同的时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。

在基本的策略模式中,选择所用具体实现的职责由客户端对象来承担,并转给策略模式的Context对象。

5、C++实现代码如下:

[cpp] view plaincopy
 
  1. #include <iostream>  
  2. using namespace std;  
  3.   
  4. //策略抽象类  
  5. class Strategy  
  6. {  
  7. public:  
  8.     virtual void AlgorithmInterface() {};  
  9. };  
  10.   
  11. //具体策略类A  
  12. class ConcreteStrategyA: public Strategy  
  13. {  
  14. public:  
  15.     void AlgorithmInterface() {  
  16.         cout << "算法A的实现" << endl;  
  17.     }  
  18. };  
  19.   
  20. //具体策略类B  
  21. class ConcreteStrategyB: public Strategy  
  22. {  
  23. public:  
  24.     void AlgorithmInterface() {  
  25.         cout << "算法B的实现" << endl;  
  26.     }  
  27. };  
  28.   
  29. //具体策略类C  
  30. class ConcreteStrategyC: public Strategy  
  31. {  
  32. public:  
  33.     void AlgorithmInterface(){  
  34.         cout << "算法C的实现" << endl;  
  35.     }  
  36. };  
  37.   
  38. //上下文类  
  39. class Context   
  40. {  
  41. private:  
  42.     //指向基类的指针  
  43.     Strategy & strategy;   
  44. public:  
  45.     Context(Strategy & s):strategy(s){};  
  46.     void ContextInterface();  
  47. };  
  48.   
  49. void Context::ContextInterface() {  
  50.     strategy.AlgorithmInterface();  
  51. }  
  52.   
  53. int main()  
  54. {  
  55.     ConcreteStrategyA a;  
  56.     ConcreteStrategyB b;  
  57.     ConcreteStrategyC c;  
  58.     Context contextA(a);  
  59.     contextA.ContextInterface();  
  60.     Context contextB(b);  
  61.     contextB.ContextInterface();  
  62.     Context contextC(c);  
  63.     contextC.ContextInterface();  
  64.     return 0;  
  65. }  

0 0
原创粉丝点击