模式定义
策略模式(Strategy Pattern):定义一系列算法,将每一个算法封装起来,并让它们可以相互替换。
UML类图
- 环境类(Context)
- 抽象策略类(Strategy)
具体策略类(ConcreteStrategy)
代码结构
public class StrategyApp { public void Run() { Context context; context = new Context(new ConcreteStrategyA()); context.ContextInterface(); context = new Context(new ConcreteStrategyB()); context.ContextInterface(); } } abstract class Strategy { public abstract void AlgorithmInterface(); } class ConcreteStrategyA : Strategy { public override void AlgorithmInterface() { Console.WriteLine( "Called ConcreteStrategyA.AlgorithmInterface()"); } } class ConcreteStrategyB : Strategy { public override void AlgorithmInterface() { Console.WriteLine("Called ConcreteStrategyB.AlgorithmInterface()"); } } class Context { private Strategy _strategy; public Context(Strategy strategy) { this._strategy = strategy; } public void ContextInterface() { _strategy.AlgorithmInterface(); } }
情景案例
定义不同的排序算法
class MainApp { static void Main() { SortedList studentRecords = new SortedList(); studentRecords.Add("Samual"); studentRecords.Add("Jimmy"); studentRecords.Add("Sandra"); studentRecords.Add("Vivek"); studentRecords.Add("Anna"); studentRecords.SetSortStrategy(new QuickSort()); studentRecords.Sort(); studentRecords.SetSortStrategy(new ShellSort()); studentRecords.Sort(); Console.ReadKey(); } } /// <summary> /// 抽象算法 /// </summary> abstract class SortStrategy { public abstract void Sort(List<string> list); } /// <summary> /// 快速排序算法 /// </summary> class QuickSort : SortStrategy { public override void Sort(List<string> list) { list.Sort(); // Default is Quicksort Console.WriteLine("QuickSorted list "); } } /// <summary> /// 插入排序 /// </summary> class ShellSort : SortStrategy { public override void Sort(List<string> list) { //list.ShellSort(); not-implemented Console.WriteLine("ShellSorted list "); } } /// <summary> /// 环境类 /// </summary> class SortedList { private List<string> _list = new List<string>(); private SortStrategy _sortstrategy; public void SetSortStrategy(SortStrategy sortstrategy) { this._sortstrategy = sortstrategy; } public void Add(string name) { _list.Add(name); } public void Sort() { _sortstrategy.Sort(_list); foreach (string name in _list) { Console.WriteLine(" " + name); } Console.WriteLine(); } }