概述

   策略模式主要应用于多种方法解决一个问题中,或一个东西有多种做法,现在只选择其中一种方法,将来可能会用另一种方法。就像一道题有多种算法,需要把这些不同的算法封装起来,达到使用无差别化。
    策略模式:策略模式针对一组算法,将每一个算法封装到具有共同接口的独立的类中,从而使得它们可以相互替换。策略模式使得算法可以在不影响到客户端的情况下发生变化。策略模式把行为和环境分开。环境类负责维持和查询行为类,各种算法在具体的策略类中提供。由于算法和环境独立开来,算法的增减,修改都不会影响到环境和客户端。

      设计

这个模式类似于Bridge模式,但是Bridge模式是为了封装实现部分,Strategy模式是为了封装某个步骤的多种算法。Strategy把这些算法抽象成一个类,直接使用其子类的对象实现具体的算法。

     实现

UML图:

 

意图 定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
适用性
  • 许多相关的类仅仅是行为有异。“策略”提供了一种用多个行为中的一个行为来配置一个类的方法。
  • 需要使用一个算法的不同变体。例如,你可能会定义一些反映不同的空间/时间权衡的算法。当这些变体实现为一个算法的类层次时[ H O 8 7 ] ,可以使用策略模式。
  • 算法使用客户不应该知道的数据。可使用策略模式以避免暴露复杂的、与算法相关的数据结构。
  • 一个类定义了多种行为, 并且这些行为在这个类的操作中以多个条件语句的形式出现。将相关的条件分支移入它们各自的S t r a t e g y 类中以代替这些条件语句。
Code Example
 1// Strategy
 2
 3// Intent: "Define a family of algorithms, encapsultate each one, and make 
 4// them interchangeable. Strategy lets the algorithm vary independently 
 5// from clients that use it." 
 6
 7// For further information, read "Design Patterns", p315, Gamma et al.,
 8// Addison-Wesley, ISBN:0-201-63361-2
 9
10/* Notes:
11 * Ideal for creating exchangeable algorithms. 
12 */

13 
14namespace Strategy_DesignPattern
15{
16    using System;
17
18    
19    abstract class Strategy 
20    {
21        abstract public void DoAlgorithm();
22    }

23
24    class FirstStrategy : Strategy 
25    {
26        override public void DoAlgorithm()
27        {
28            Console.WriteLine("In first strategy");            
29        }

30    }

31
32    class SecondStrategy : Strategy 
33    {
34        override public void DoAlgorithm()
35        {
36            Console.WriteLine("In second strategy");            
37        }

38    }

39
40    class Context 
41    {
42        Strategy s;
43        public Context(Strategy strat)
44        {
45            s = strat;            
46        }

47
48        public void DoWork()
49        {
50            // some of the context's own code goes here
51        }

52
53        public void DoStrategyWork()
54        {
55            // now we can hand off to the strategy to do some 
56            // more work
57            s.DoAlgorithm();
58        }

59    }

60
61    /// <summary>
62    ///    Summary description for Client.
63    /// </summary>

64    public class Client
65    {
66        public static int Main(string[] args)
67        {    
68            FirstStrategy firstStrategy = new FirstStrategy();
69            Context c = new Context(firstStrategy);
70            c.DoWork();
71            c.DoStrategyWork();
72
73            return 0;
74        }

75    }

76}

77
78

还有一个示例代码为:

 1using System;
 2using System.Collections ;
 3
 4namespace Example
 5{
 6    /// <summary>
 7    /// 示例
 8    /// </summary>

 9    class Example
10    {
11        /// <summary>
12        /// 应用程序的主入口点。
13        /// </summary>

14        [STAThread]
15        static void Main(string[] args)
16        {
17            Context c = new Context() ;
18            c.ContextInterface() ;
19        }

20        /// <summary>
21        /// 使用策略的类
22        /// </summary>

23        public class Context
24        {
25            private Strategy s = null ;
26            public void ContextInterface()
27            {
28                s = new ConcreteStrategyB() ;//决定使用哪个策略
29                s.AlgorithmInterface() ;
30            }

31        }

32        /// <summary>
33        /// 策略抽象类,封装实现策略的接口
34        /// </summary>

35        public abstract class Strategy
36        {
37            public abstract void AlgorithmInterface() ;
38        }

39        /// <summary>
40        /// A策略
41        /// </summary>

42        public class ConcreteStrategyA : Strategy
43        {
44            public override void AlgorithmInterface()
45            {
46                Console.WriteLine( "实现A算法" ) ;
47            }

48        }

49        /// <summary>
50        /// B策略
51        /// </summary>

52        public class ConcreteStrategyB : Strategy
53        {
54            public override void AlgorithmInterface()
55            {
56                Console.WriteLine( "实现B算法" ) ;
57            }

58        }

59        /// <summary>
60        /// C策略
61        /// </summary>

62        public class ConcreteStrategyC : Strategy
63        {
64            public override void AlgorithmInterface()
65            {
66                Console.WriteLine( "实现C算法" ) ;
67            }

68        }

69    }

70}