为什么实验楼网站上做实验这么卡,微服务网站,郑州公司做网站,o2o商业模式Unity实现设计模式——策略模式
策略模式是一种定义一些列算法的方法#xff0c;这些所有的算法都是完成相同的工作#xff0c;只是实现不同。它可以通过相同的方式调用所有的算法#xff0c;减少各种算法类与使用算法类之间的耦合。
策略模式的 Strategy 类层次为 Contex…Unity实现设计模式——策略模式
策略模式是一种定义一些列算法的方法这些所有的算法都是完成相同的工作只是实现不同。它可以通过相同的方式调用所有的算法减少各种算法类与使用算法类之间的耦合。
策略模式的 Strategy 类层次为 Context 定义了一系列的可供重用的算法或行为。继承有助于析取出这些算法中的公共功能。
策略模式就是用来封装算法的但在实践中我们发现可以用它来封装几乎任何类型的规则只要在分析过程中听到需要在不同时间应用不同的业务规则就可以考虑使用策略模式处理这种变化的可能性。
需要注意的是策略模式与工厂模式的区别 简单工厂模式下产品类父类里包含了产品的属性所以每个具体产品子类也就包含了同样的属性。 策略模式下策略类父类里只提供了虚方法并没有包含属性所以每个具体的算法有自己独立的属性。 下面使用对于一个结构进行排序的例子来演示
1.SortStrategyThe ‘Strategy’ abstract class abstract class SortStrategy{public abstract void Sort(Liststring list);}2.派生类
1QuickSort class QuickSort : SortStrategy{public override void Sort(Liststring list){list.Sort(); // Default is QuicksortDebug.Log(-------QuickSorted list------- );}}2ShellSort class ShellSort : SortStrategy{public override void Sort(Liststring list){//list.ShellSort(); not-implementedDebug.Log(-------ShellSorted list------- );}}3MergeSort class MergeSort : SortStrategy{public override void Sort(Liststring list){//list.MergeSort(); not-implementedDebug.Log(-------MergeSorted list------- );}}3.SortedListThe ‘Context’ class class SortedList{private Liststring _list new Liststring();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);// Iterate over list and display resultsforeach (string name in _list){Debug.Log( name);}}}4.测试 public class StrategyPatternExample1 : MonoBehaviour{void Start(){// Two contexts following different strategiesSortedList 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();studentRecords.SetSortStrategy(new MergeSort());studentRecords.Sort();}}