2.大话设计模式-策略模式

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace DesignModel
 8 {
 9     /// <summary>
10     /// 策略模式
11     /// </summary>
12     public class TacticsModel
13     {
14         //对于策略模式的理解:当一个业务有多种需求时候,在某个时候需要使用不同的方式来计算结果。这时候不同的方式可以理解为
15         //不同的策略来解决同样的问题。 例如:商场收银系统计算价格,1:正常计算 2:商品打折计算,3:满300减100等方式。就可以
16         //按三种策略来处理需求。
17         //简单的说:策略模式就是用来封装算法的,但在实践中,我们发现可以用他来封装几乎任何类型的规则,只要在分析过程中听到需要
18         //在不同的时间应用不同的业务规则,就可以考虑使用策略模式处理这种变化的可能性。
19 
20         public string type { get; set; }
21 
22         public virtual string GetResult()
23         {
24             return "";
25         }
26 
27     }
28 
29     public class Normal:TacticsModel
30     {
31         public override string GetResult()
32         {
33             return "正常计算价格";
34         }
35     }
36     public class Discount : TacticsModel
37     {
38         public override string GetResult()
39         {
40             return "按打折计算价格";
41         }
42     }
43     public class Preferential : TacticsModel
44     {
45         public override string GetResult()
46         {
47             return "满300减100活动";
48         }
49     }
50 
51 
52 
53     public class CashContext
54     {
55         TacticsModel tm = null;
56 
57         public CashContext(string type)
58         {
59             switch (type)
60             {
61                 case "1":
62                     tm = new Normal();
63                     break;
64                 case "2":
65                     tm = new Discount();
66                     break;
67                 case "3":
68                     tm = new Preferential();
69                     break;
70 
71                 default:
72                 break;
73              }
74         }
75 
76         public string GetResult()
77         {
78             return tm.GetResult();
79         }
80     }
81 }

这种方式和简单工厂方式差不多,只是有稍微区别。 简单工厂模式需要暴漏给客户端两个类,策略模式和工厂模式的简单结合只暴漏了一个CashContext

 

客户端调用代码:

1             Console.WriteLine("请计算类型1正常,2打折,3优惠:");
2             string type = Console.ReadLine();
3 
4             CashContext cc = new CashContext(type);
5             Console.WriteLine(cc.GetResult());

结果:

 

其中还是使用了swich ,也就是就是说增加一种需求就有更改swith语句,很是不爽,不过任何需求的变更都是需要成本的。

只是成本的高低是有区别的。这个地方用反射技术会有更好的效果。后续会补充。

 

本系列文章是根据大话设计模式誊写的。如果想学习的更全面可以参考大话设计模式

posted @ 2014-07-19 15:33  Mountains  阅读(288)  评论(0编辑  收藏  举报