此模式意图在于切换算法,其实现方式与模板模式,桥接模式等是大同小异,或者可以说是相同,只有意图不同而已.初学设计模式都被这相似的代码,不同的模式搞混乱了。其实仅仅就是抽象而已。
1.接口与实现
// Strategy interface interface IStrategy { int Move (Context c); } // Strategy 1 class Strategy1 : IStrategy { public int Move (Context c) { return ++c.Counter; } } // Strategy 2 class Strategy2 : IStrategy { public int Move (Context c) { return --c.Counter ; } }
2.上下文的一个类
class Context { // Context state public const int start = 5; public int Counter = 5; // Strategy aggregation IStrategy strategy = new Strategy1(); // Algorithm invokes a strategy method public int Algorithm() { return strategy.Move(this); } // Changing strategies public void SwitchStrategy() { if (strategy is Strategy1) strategy = new Strategy2(); else strategy = new Strategy1(); } }
3.客户端调用
static class Program { static void Main () { Context context = new Context(); context.SwitchStrategy(); Random r = new Random(37); for (int i=Context.start; i<=Context.start+15; i++) { if (r.Next(3) == 2) { Console.Write("|| "); context.SwitchStrategy(); } Console.Write(context.Algorithm() +" "); } Console.WriteLine(); Console.ReadKey(); } }
其实就是这么简单.当然还有很多变态体,知道其是干什么就可以了