设计模式之策略模式

策略模式意图:定义一系列的算法,把它们一个个封装起来,并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。

动机:有许多算法可对一个功能进行处理,将这些算法硬编进使用它们的类中是不可取的,其原因:

(1)、需要该功能的客户程序如果直接包含处理算法代码的话将会变得复杂,这使得客户程序庞大并且难以维护,尤其当其需要支持多种算法时会更加严重

(2)、不同的时候需要不同的算法,我们不想支持我们并不使用的算法

(3)、当功能是客户程序的一个难以分割的成分时,增加新的算法或改变现有算法将十分困难

结构图:

下面是自己所想的一个小程序,实现策略模式的功能,code如下:

代码
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading;
 6 
 7 namespace Strategy
 8 {
 9     //client类
10     class Program
11     {
12         static void Main(string[] args)
13         {
14             LoseWeight lw = null;
15             Console.WriteLine("Please input girls or boys!");
16             string strSex = Console.ReadLine();
17             if (strSex == "girls")
18             {
19                 lw = new LoseWeight(new KeepDiet());
20             }
21             if(strSex=="boys")
22             {
23                 lw = new LoseWeight(new Exercise());
24             }
25             lw.ExecLoseWeight();
26             Thread.Sleep(2000);
27         }
28     }
29 
30     //strategy接口
31     interface ILoseWeight
32     { 
33         //减肥
34         void LoseWeight();
35     }
36 
37     //男生选择锻炼健美
38     class Exercise : ILoseWeight
39     {
40         public void LoseWeight()
41         {
42             Console.WriteLine("exercise to lose weight!");
43         }
44     }
45 
46     //女生选择控制饮食保持体形
47     class KeepDiet : ILoseWeight
48     {
49         public void LoseWeight()
50         {
51             Console.WriteLine("keep on a diet to lose weight!");
52         }
53     }
54 
55     //context类
56     class LoseWeight
57     {
58         ILoseWeight iLoseWeight;
59         
60         public LoseWeight() { }
61         public LoseWeight(ILoseWeight iLoseWeight)
62         {
63             this.iLoseWeight = iLoseWeight;
64         }
65 
66         public void ExecLoseWeight()
67         {
68             iLoseWeight.LoseWeight();
69         }
70     }
71 }
72 

这段code中由client类决定哪个concretestrategy类被创建,但我看过一本书《C# 3.0设计模式》,书中作者在P153页是这样讲解的:Context常常会包含一条switch或者一连串的if语句,在这些语句中处理相关信息并做出采用何种Strategy的决定。让我有点疑惑,到底是由Client类还是Context决定concretestrategy,个人感觉还是Client类决定比较好,这样Context就不需要做过多处理,而Client类知道根据具体情况来选择哪个concretestrategy的创建。不知大家是如何看的呢,不吝赐教!

原文地址:https://www.cnblogs.com/qingliuyu/p/1744810.html