策略模式+简单工厂模式


策略模式实现方式

a) 提供公共接口或抽象类,定义需要使用的策略方法。(策略抽象类)

b) 多个实现的策略抽象类的实现类。(策略实现类)

c) 环境类,对多个实现类的封装,提供接口类型的成员量,可以在客户端中切换。

d) 客户端 调用环境类 进行不同策略的切换。

策略模式的优点

1、策略模式提供了管理相关的算法族的办法。策略类的等级结构定义了一个算法或行为族。恰当使用继承可以把公共的代码移到父类里面,从而避免代码重复。

2、使用策略模式可以避免使用多重条件(if-else)语句。多重条件语句不易维护,它把采取哪一种算法或采取哪一种行为的逻辑与算法或行为的逻辑混合在一起,统统列在一个多重条件语句里面,比使用继承的

办法还要原始和落后。


策略模式的缺点
1、客户端必须知道所有的策略类,并自行决定使用哪一个策略类。这就意味着客户端必须理解这些算法的区别,以便适时选择恰当的算法类。换言之,策略模式只适用于客户端知道算法或行为的情况。

2、由于策略模式把每个具体的策略实现都单独封装成为类,如果备选的策略很多的话,那么对象的数目就会很可观。

实现例子如下:

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Text;
 4 
 5 namespace ConsoleApp1
 6 {
 7     /// <summary>
 8     /// 算法基类
 9     /// </summary>
10     public class arithmetic
11     {
12         public int A { get; set; }
13 
14         public int B { get; set; }
15 
16         public virtual int operation()
17         {
18             return 0;
19         }
20     }
21 
22     /// <summary>
23     /// 加法
24     /// </summary>
25     public class arithmeticAdd : arithmetic
26     {
27         public override int operation()
28         {
29             return A + B;
30 
31         }
32     }
33 
34     /// <summary>
35     /// 减法
36     /// </summary>
37     public class arithmeticSubtraction : arithmetic
38     {
39         public override int operation()
40         {
41             return A - B;
42         }
43     }
44 
45     /// <summary>
46     /// 策略类
47     /// </summary>
48     public class context
49     {
50         private arithmetic op;
51         public context(string type)
52         {
53             switch (type)
54             {
55                 case "+": { op = new arithmeticAdd(); };break;
56                 case "-": { op = new arithmeticSubtraction(); }; break;
57             }
58         }
59 
60         public int getResult()
61         {
62             return op.operation();
63         }
64     }
65 
66 }
原文地址:https://www.cnblogs.com/liangdejiu/p/11250688.html