状态模式重构条件语句
直接上代码:

/// <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

客户端调用:

#region 状态模式重构switch...case...
static void SwitchToStateDP()
{
    var ctx = new CalculateContext();
    ctx.CalculateAmount();

    ctx.SetAddress(new GetFloridaShippingAmount());
    ctx.CalculateAmount();
}
#endregion

状态模式:当一个对象的内部状态改变时允许改变它的行为。状态模式主要解决的是当控制一个对象状态转换的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类当中,可以把复杂的判断逻辑简化。
客户端通过SetAddress(对应状态模式中的内部状态改变)来调整客户的选择(也就是条件)。

相关文章:

  • 2021-10-17
  • 2021-12-09
  • 2021-12-10
  • 2021-12-29
  • 2022-12-23
  • 2021-07-10
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-08-28
  • 2021-07-28
  • 2021-12-26
  • 2021-11-21
  • 2022-12-23
  • 2021-08-04
  • 2021-07-06
相关资源
相似解决方案