设计模式(二):策略模式

时间:2023-01-19 22:02:19
策略模式(Strategy):它定义了一个算法家族,分别封装起来,让它们之间可以互相替换,此模式让算法的变化,不会影响到使用算法的客户。
    /// <summary>
/// 现金收费抽象类
/// </summary>
abstract class CashSuper
{
public abstract double AcceptCash(double money);
}
    /// <summary>    /// 正常收费子类    /// </summary>    class CashNormal : CashSuper    {        public override double AcceptCash(double money)        {            return money;        }    }
    /// <summary>    /// 打折收费子类    /// </summary>    class CashRebate : CashSuper    {        private  double _moneyRebate = 1d;        public CashRebate(string moneyRebate)        {            this._moneyRebate = double.Parse(moneyRebate);        }        public override double AcceptCash(double money)        {            return money*_moneyRebate;        }    }
    /// <summary>    /// 返利收费子类    /// </summary>    class CashReturn : CashSuper    {        private double moneyCondition = 0.0d;        private double moneyReturn = 0.0d;        public CashReturn(string moneyCondition,string moneyReturn)        {            this.moneyCondition = double.Parse(moneyCondition);            this.moneyReturn = double.Parse(moneyReturn);        }        public override double AcceptCash(double money)        {            double result = money;            if (money >= moneyCondition)                result = money - Math.Floor(money/moneyCondition)*moneyReturn;            return result;        }    }
    /// <summary>    /// 判断    /// </summary>    class CashContext    {        private CashSuper cs = null;        public CashContext(string type)        {            switch (type)            {                case "正常收费":                    cs = new CashNormal();                    break;                case "满300返100":                    cs = new CashReturn("300","100");                    break;                case "打8折":                    cs = new CashRebate("0.8");                    break;            }        }        public double GetResult(double money)        {            return cs.AcceptCash(money);        }    }
    /// <summary>    /// 程序主体    /// </summary>    class Program    {        static void Main(string[] args)        {            Console.Write("请输入类型:");            var type = Console.ReadLine();            Console.Write("请输入金额:");            var money = Console.ReadLine();            var cs = new CashContext(type);            Console.WriteLine("需付金额:"+cs.GetResult(double.Parse(money)));            Console.ReadLine();        }    }

运行结果:

设计模式(二):策略模式