索引
定义一系列的算法,把它们一个个封装起来,并且使它们可以相互替换。使得算法可独立于使用它的客户而变化。
Define a family of algorithms, encapsulate each one, and make them interchangeable.
Strategy lets the algorithm vary independently from clients that use it.
Strategy
ConcreteStrategy
Context
在以下情况下可以使用 Strategy 模式:
实现方式(一):使用不同的 Strategy 处理内部状态。
Strategy 和 Context 接口必须使得 ConcreteStrategy 能够有效的访问它所需要的 Context 中的任何数据。
一种办法是让 Context 将数据放在参数中传递给 Strategy 操作。这使得 Strategy 和 Context 解耦。
但另一方面,Context 可能发送一些 Strategy 不需要的数据。
另一种办法是让 Context 将自身作为一个参数传递给 Strategy,该 Strategy 再显式地向该 Context 请求数据。
或者 Strategy 可以直接保存对 Context 的引用。
这种情况下,Strategy 可以请求到它需要的数据。但这使得 Strategy 和 Context 更紧密的耦合在一起。
1 namespace StrategyPattern.Implementation1 2 { 3 public abstract class Strategy 4 { 5 public abstract void AlgorithmInterface(string state); 6 } 7 8 public class ConcreteStrategyA : Strategy 9 { 10 public override void AlgorithmInterface(string state) 11 { 12 Console.WriteLine("Use Concrete Strategy A to handle " + state); 13 } 14 } 15 16 public class ConcreteStrategyB : Strategy 17 { 18 public override void AlgorithmInterface(string state) 19 { 20 Console.WriteLine("Use Concrete Strategy B to handle " + state); 21 } 22 } 23 24 public class Context 25 { 26 private Strategy _strategy; 27 28 public void SetStrategy(Strategy strategy) 29 { 30 _strategy = strategy; 31 } 32 33 public string State { get; set; } 34 35 public void ContextInterface() 36 { 37 _strategy.AlgorithmInterface(State); 38 } 39 } 40 41 public class Client 42 { 43 public void TestCase1() 44 { 45 var context = new Context(); 46 context.State = "Hello World"; 47 48 context.SetStrategy(new ConcreteStrategyA()); 49 context.ContextInterface(); 50 51 context.SetStrategy(new ConcreteStrategyB()); 52 context.ContextInterface(); 53 } 54 } 55 }
《设计模式之美》为 Dennis Gao 发布于博客园的系列文章,任何未经作者本人同意的人为或爬虫转载均为耍流氓。
设计模式之美:Strategy(策略),布布扣,bubuko.com
原文:http://www.cnblogs.com/gaochundong/p/design_pattern_strategy.html