首页 > 代码库 > 策略模式

策略模式

  核心要点:策略模式对于使用者来说是白盒,而工厂模式对于使用者来说,是黑盒。

    /// <summary>    /// 操作基类    /// </summary>    public class Operation    {        private double _numberA = 0;        private double _numberB = 0;        public double NumberA        {            get { return _numberA; }            set { _numberA = value; }        }        public double NumberB        {            get { return _numberB; }            set { _numberB = value; }        }        public virtual double GetResult()        {            return 0;        }    }    /// <summary>    /// 具体操作类    /// </summary>    public class OperationAdd : Operation    {        public override double GetResult()        {            double result = 0;            result = NumberA + NumberB;            return result;        }    }    public class OperationSub : Operation    {        public override double GetResult()        {            double result = 0;            result = NumberA - NumberB;            return result;        }    }    /// <summary>    /// 工厂根据需求生产某一类型的事物    /// </summary>    public class Student    {        private Operation func = null;        public void ApplyOperation(string operate)        {            switch(operate)            {                case "+":                    this.func = new OperationAdd();                    break;                case "-":                    this.func = new OperationSub();;                    break;            }        }        public double GetResult(double numberA, double numberB)        {            func.NumberA = numberA;            func.NumberB = numberB;            return func.GetResult();        }    }    class Program    {        static void Main(string[] args)        {            var XiaoMing = new Student();            XiaoMing.ApplyOperation("+");            var add_result = XiaoMing.GetResult(1, 2);            Console.WriteLine("result is:" + add_result);            XiaoMing.ApplyOperation("-");            var sub_result = XiaoMing.GetResult(7, 2);            Console.WriteLine("result is:" + sub_result);            Console.Read();        }    }

  可以看到,对外部来说,只有 Student 这个类型暴露在外面,由自己完成策略授权与结果计算。

  而对比之前得工厂模式,工厂与使用者同时暴露在外面,由工厂授权,使用者直接计算结果而不用了解计算过程。

策略模式