C#版本
设计模式的规则:
一、面向接口编程,而不是面向实现编程
二、将可能的变化提取出来。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApplication1 { abstract class Strategy /**策略抽象类**/ { public abstract void AlgorithmInterface();/**算法**/ } class ConcreteStrategyA:Strategy /**A算法**/ { public override void AlgorithmInterface() { Console.WriteLine("算法A实现"); } } class ConcreteStrategyB : Strategy /**B算法**/ { public override void AlgorithmInterface() { Console.WriteLine("算法B实现"); } } class Context /**上下文类产生算法实例对象**/ { Strategy strategy; public Context(string index) /**构造函数**/ { switch(index)/**将前端的判断也移到后端实现**/ { case "1": strategy = new ConcreteStrategyA(); break; case "2": strategy = new ConcreteStrategyB(); break; } } public void GetResult() /**执行算法**/ { strategy.AlgorithmInterface(); } } class Program { static void Main(string[] args) { /**前端调用,已经看不到任何实现,只有选择**/ Context context = new Context("1");/**执行算法A**/ context.GetResult(); } } }