策略模式(Strategy Pattern)

Posted LoveTomato

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了策略模式(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();
		}
	}

以上是关于策略模式(Strategy Pattern)的主要内容,如果未能解决你的问题,请参考以下文章

1.Strategy Pattern(策略模式)

java设计模式行为模式Behavioral Pattern策略模式Strategy Pattern

设计模式-策略模式(strategy pattern)

策略模式(Strategy Pattern)

策略模式(Strategy Pattern)

策略模式(strategy-pattern)