如果用一句话来概括简单工厂模式那便是:简单工厂模式解决了程序在运行时需要生成什么样的类来调用。那么策略模式要解决的就是,在程序运行时执行的方法当中,用什么样的算法来解决实际中产生的问题。
策略模式:它定义了算法家族,分别封装起来,让它们之间可以相互替换,此模式让算法的变化,不会影响到使用算法的客户。
实例:超市打折促销中的多种手段(一会儿打85折,一会儿9折,一会儿满25减5……),这些手段都是叫折扣(discount/on sale),只是具体的算法不一样而已。
其实现形式大体概括(用自己的话)便是:
创建一个抽象类,在抽象类中声明一个抽象方法,然后再让继承抽象类的子类去实现这个抽象方法!


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Strategy { abstract class Strategy { public abstract void AlgorithmInterface(); } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Strategy { class ConcreateStrategyA : Strategy { public override void AlgorithmInterface() { Console.Write("商品以85这促销!"); } } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Strategy { class ConcreateStrategyB : Strategy { public override void AlgorithmInterface() { Console.Write("商品以9折促销!"); } } }


using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Strategy { class ConcreateStrategyC:Strategy { public override void AlgorithmInterface() { Console.Write("商品满25减5!"); } } }



using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Strategy { class Program { static void Main(string[] args) { Context context = new Context("");//传入"85","9"或者"25-5" context.ContextInterface(); } } }
在简单工厂类中,使用了switch判断传入的type来生成相应的对象,当需要增加一个方法的时候,就需要为switch语句增加一个条件分支。这里可以使用反射来消除这里大量的switch判断,当需要增加一个方法的时候,只需要在config文件中进行配置就可以了!
——抽象工厂模式