Switch to strategy

时间:2021-09-09 14:28:53

Switch to strategy

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;
}
}
}

Switch to strategy

Switch to strategy

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;
}
}
}

参考:Refactoring Day 11 : Switch to Strategy