策略模式(Strategy)

 1 /*
 2  * 在图书销售时,根据不同类型的图书有不同的折扣,计算金额时必须区别对待,
 3  * 例如计算机类图书7折,英语类图书6折。应用策略模式,用C#控制台应用程序
 4  * 实现该设计。
 5  */
 6 using System;
 7 using System.Collections.Generic;
 8 using System.Linq;
 9 using System.Text;
10 
11 namespace Strategy
12 {
13     abstract class Strategy
14     {
15         public abstract double AlgorithmInterface(double Money);
16     }
17     class CSStrategy : Strategy
18     {
19           public override double AlgorithmInterface(double Money)
20         {
21             Console.WriteLine("计算机类书打七折。");
22             return (Money*0.7);
23         }
24     }
25     class EngStrategy : Strategy
26     {
27        public override double AlgorithmInterface(double Money)
28         {
29             Console.WriteLine("英语类书打六折。");
30             return (Money * 0.6);
31         }
32     }
33     class Context
34     {
35         Strategy strategy;
36         public Context(Strategy strategy)
37         {
38             this.strategy = strategy;
39         }
40         public double GetResult(double Money)
41         {
42             return strategy.AlgorithmInterface(Money);
43         }
44     }
45     class Program
46     {
47         static void Main(string[] args)
48         {
49             Context context;
50             context = new Context(new CSStrategy());
51             Console.WriteLine("需支付" + context.GetResult(100) + "");
52 
53             context = new Context(new EngStrategy());
54             Console.WriteLine("需支付" + context.GetResult(100) + "");
55         }
56     }
57 }

 

posted @ 2012-05-16 23:37  ZH奶酪  阅读(577)  评论(0编辑  收藏  举报