设计模式——策略模式

名称 Strategy
结构  
意图 定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。
适用性
  • 许多相关的类仅仅是行为有异。“策略”提供了一种用多个行为中的一个行为来配置一个类的方法。
  • 需要使用一个算法的不同变体。例如,你可能会定义一些反映不同的空间/时间权衡的算法。当这些变体实现为一个算法的类层次时[ 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
原文地址:https://www.cnblogs.com/DarkAngel/p/217265.html