策略模式

模板方法模式:流程固定,但构成流程的每个步骤可以子类化多态;策略模式:消除平行结构,将其拆成多个策略算法类,由调用者选择

软件构建过程中有许多算法,但在算法实现时经常改变,编写在程序里会很麻烦

例如:纳税的计算,在写代码时需计算的国家数量较少,在之后会增加,

 

以如下这种if,else的方式确实可以实现所需的功能

trategy1.cpp

 1 enum TaxBase {
 2     CN_Tax,
 3     US_Tax,
 4     DE_Tax,
 5     FR_Tax       //更改
 6 };
 7 
 8 class SalesOrder{
 9     TaxBase tax;
10 public:
11     double CalculateTax(){
12         //...
13         
14         if (tax == CN_Tax){
15             //CN***********
16         }
17         else if (tax == US_Tax){
18             //US***********
19         }
20         else if (tax == DE_Tax){
21             //DE***********
22         }
23         else if (tax == FR_Tax){  //更改
24             //...
25         }
26 
27         //....
28      }
29     
30 }; 

 

实现复用性是编译单位,二进制层面的复用,不是粘贴复制的。

在需要增加其他国家税法时,trategy1.cpp需要在源代码增加所需的功能,打破了封闭原则

在trategy2.cpp中通过纯虚函数和指针多态的方式实现,将不同的算法 一个个封装起来(变化),使算法可以独立于客户程序(稳定)

trategy2.cpp

 1 class TaxStrategy{
 2 public:
 3     virtual double Calculate(const Context& context)=0;                       
 4     virtual ~TaxStrategy(){}
 5 };
 6 
 7 
 8 class CNTax : public TaxStrategy{
 9 public:
10     virtual double Calculate(const Context& context){
11         //***********
12     }
13 };
14 
15 class USTax : public TaxStrategy{
16 public:
17     virtual double Calculate(const Context& context){
18         //***********
19     }
20 };
21 
22 class DETax : public TaxStrategy{
23 public:
24     virtual double Calculate(const Context& context){
25         //***********
26     }
27 };
28 
29 
30 
31 //扩展
32 //*********************************
33 class FRTax : public TaxStrategy{
34 public:
35     virtual double Calculate(const Context& context){
36         //.........
37     }
38 };
39 
40 
41 class SalesOrder{
42 private:
43     TaxStrategy* strategy;
44 
45 public:
46     SalesOrder(StrategyFactory* strategyFactory){
47         this->strategy = strategyFactory->NewStrategy();
48     }
49     ~SalesOrder(){
50         delete this->strategy;
51     }
52 
53     public double CalculateTax(){
54         //...
55         Context context();
56 
57         double val =
58             strategy->Calculate(context); //多态调用
59         //...
60     }
61 
62 };

 

posted @ 2021-02-09 22:18  miaorn  阅读(118)  评论(0编辑  收藏  举报