结构 | ![]() |
意图 | 定义一系列的算法,把它们一个个封装起来, 并且使它们可相互替换。本模式使得算法可独立于使用它的客户而变化。 |
适用性 |
|
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
![](https://images.cnblogs.com/OutliningIndicators/ExpandedBlockStart.gif)
1 using System; 2 3 4 abstract class Strategy 5 { 6 abstract public void DoAlgorithm(); 7 } 8 9 class FirstStrategy : Strategy 10 {11 override public void DoAlgorithm()12 {13 Console.WriteLine("In first strategy"); 14 }15 }16 17 class SecondStrategy : Strategy 18 {19 override public void DoAlgorithm()20 {21 Console.WriteLine("In second strategy"); 22 }23 }24 25 class Context 26 {27 Strategy s;28 public Context(Strategy strat)29 {30 s = strat; 31 }32 33 public void DoWork()34 {35 // some of the context's own code goes here36 }37 38 public void DoStrategyWork()39 {40 // now we can hand off to the strategy to do some 41 // more work42 s.DoAlgorithm();43 }44 }45 46 ///47 /// Summary description for Client.48 /// 49 public class Client50 {51 public static int Main(string[] args)52 { 53 FirstStrategy firstStrategy = new FirstStrategy();54 Context c = new Context(firstStrategy);55 c.DoWork();56 c.DoStrategyWork();57 58 return 0;59 }60 }