状态模式重构条件语句 直接上代码:
代码语言:javascript复制/// <summary>
/// 状态模式的环境类
/// </summary>
public class CalculateContext
{
private IShippingAmount _Calculate;
public CalculateContext() => _Calculate = new GetAlaskaShippingAmount();
public void SetAddress(IShippingAmount calculate) => _Calculate = calculate;
public decimal CalculateAmount() => _Calculate.GetAmount();
}
// 抽象
public interface IShippingAmount
{
AddressState State { get; }
decimal GetAmount();
}
#region 具体地址的实现
// 具体
public class GetAlaskaShippingAmount : IShippingAmount
{
public AddressState State { get => AddressState.Alaska; }
public decimal GetAmount() => 15;
}
public class GetNewYorkShippingAmount : IShippingAmount
{
public AddressState State { get => AddressState.NewYork; }
public decimal GetAmount() => 10;
}
public class GetFloridaShippingAmount : IShippingAmount
{
public AddressState State { get => AddressState.Florida; }
public decimal GetAmount() => 3;
}
#endregion
客户端调用:
代码语言:javascript复制#region 状态模式重构switch...case...
static void SwitchToStateDP()
{
var ctx = new CalculateContext();
ctx.CalculateAmount();
ctx.SetAddress(new GetFloridaShippingAmount());
ctx.CalculateAmount();
}
#endregion
状态模式:当一个对象的内部状态改变时允许改变它的行为。状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类当中,可以把复杂的判断逻辑简化。 客户端通过SetAddress(对应状态模式中的内部状态改变)来调整客户的选择(也就是条件)。