| 名称 | Strategy |
| 结构 | ![]() |
| 意图 | 定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。 |
| 适用性 |
|
| Code Example |
1 // Strategy2 ![]() 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-29 ![]() 10 /* Notes:11 * Ideal for creating exchangeable algorithms. 12 */13 14 namespace Strategy_DesignPattern15 {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 here51 }52 ![]() 53 public void DoStrategyWork()54 {55 // now we can hand off to the strategy to do some 56 // more work57 s.DoAlgorithm();58 }59 }60 ![]() 61 /// <summary>62 /// Summary description for Client.63 /// </summary>64 public class Client65 {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 ![]() |




* Ideal for creating exchangeable algorithms.


}