前进中的蜗牛

番茄大叔

水滴穿石,非一日之功;没有量变,何来质变。

策略模式(Strategy Pattern)

模式定义

策略模式(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();
		}
	}
posted @ 2018-02-13 17:48  LoveTomato  阅读(170)  评论(0编辑  收藏  举报