策略模式重构条件语句

通过策略模式来重构优化代码里面的switch/case分支代码。极大程度上提高了程序的扩展性。当然,如果分支比较多,每次都需要新增加一个类,这的确是有点麻烦,可以考虑使用反射来实现。
代码:

namespace DP
{
    public enum State
    {
        Alaska,
        NewYork,
        Florida
    }

    public class CalculateShippingAmount 
    {
        public CalculateShippingAmount(IDictionary<State, IGetShippingAmount> dic) => _dic = dic;

        private IDictionary<State, IGetShippingAmount> _dic { get; set; }

        public decimal Calculate(State state) => _dic[state].GetAmount();
    }

    public interface IGetShippingAmount
    {
        decimal GetAmount();
    }

    #region 具体地址的实现
    // 具体
    public class GetAlaskaShippingAmount : IGetShippingAmount
    {
        public decimal GetAmount() => 15;
    }

    public class GetNewYorkShippingAmount : IGetShippingAmount
    {
        public decimal GetAmount() => 10;
    }

    public class GetFloridaShippingAmount : IGetShippingAmount
    {
        public decimal GetAmount() => 3;
    }
    #endregion

}

调用:

#region 策略模式重构 switch...case...
        static void SwitchToStrategy()
        {
            var dic = new Dictionary<State, IGetShippingAmount>
            {
                {State.Alaska,  new GetAlaskaShippingAmount() },
                {State.Florida, new GetFloridaShippingAmount() },
                {State.NewYork, new GetNewYorkShippingAmount() }
            };

            var calculate = new CalculateShippingAmount(dic);
            var result = calculate.Calculate(State.Florida);
            Console.WriteLine($"{State.Florida.ToString()}返回{result}");
        }
        #endregion

参考:使用策略模式重构switch case 代码

转载于:https://www.cnblogs.com/zhiyong-ITNote/p/10981236.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值