Switch to strategy

Switch To Strategy (before) 

namespace RefactoringLib.SwitchToStrategy.Before
{
    public class ClientCode
    {
        public decimal CalculateShipping()
        {
            ShippingInfo shippingInfo = new ShippingInfo();
            return shippingInfo.CalculateShippingAmount(State.Alaska);
        }
    }

    public enum State
    {
        Alaska,
        NewYork,
        Florida
    }

    public class ShippingInfo
    {
        public decimal CalculateShippingAmount(State shipToState)
        {
            switch (shipToState)
            {
                case State.Alaska:
                    return GetAlaskaShippingAmount();

                case State.NewYork:
                    return GetNewYorkShippingAmount();

                case State.Florida:
                    return GetFloridaShippingAmount();

                default:
                    return 0m;
            }
        }

        private decimal GetAlaskaShippingAmount()
        {
            return 15m;
        }

        private decimal GetNewYorkShippingAmount()
        {
            return 10m;
        }

        private decimal GetFloridaShippingAmount()
        {
            return 3m;
        }
    }
}
View Code

 

Switch To Strategy (end)

namespace RefactoringLib.SwitchToStrategy.End
{
    public class ClientCode
    {
        public decimal CalculateShipping()
        {
            ShippingInfo shippingInfo = new ShippingInfo();
            return shippingInfo.CalculateShippingAmount(State.Alaska);
        }
    }

    public enum State
    {
        Alaska,
        NewYork,
        Florida
    }

    public class ShippingInfo
    {
        public IDictionary<State, IShippingCalculaton> ShippingCalculatons { get; set; }

        public ShippingInfo()
        {
            ShippingCalculatons = new Dictionary<State, IShippingCalculaton> 
            {
                { State.Alaska, new AlaskaShippingCalculation() },
                { State.NewYork, new NewYorkShippingCalculation() },
                { State.Florida, new FloridaShippingCalculation() }
            };
        }

        public decimal CalculateShippingAmount(State state)
        {
            return ShippingCalculatons[state].Calculate();
        }
    }

    public interface IShippingCalculaton
    {
        decimal Calculate();
    }

    public class AlaskaShippingCalculation : IShippingCalculaton
    {
        public decimal Calculate()
        {
            return 15m;
        }
    }

    public class NewYorkShippingCalculation : IShippingCalculaton
    {
        public decimal Calculate()
        {
            return 10m;
        }
    }

    public class FloridaShippingCalculation : IShippingCalculaton
    {
        public decimal Calculate()
        {
            return 5m;
        }
    }
}
View Code

 

 参考:Refactoring Day 11 : Switch to Strategy

 

posted on 2013-12-06 10:56  backslash112  阅读(202)  评论(0编辑  收藏  举报

导航