购物车中的付款策略

时间:2012-06-24 07:58:13

标签: design-patterns c#-4.0 e-commerce

什么是最合适的模式,可用于以下方法。我倾向于使用switch语句的策略模式,但if是如何。如果我有不同类型的折扣,我也应该使用策略模式呢?

public void AddOrder(PaymentType paymentType, OrderType orderType)
{
    if (orderType == OrderType.Sale)
    {
        switch (paymentType)
        {
            case PaymentType.Cash:
                // Do cash calculations here
                break;
            case PaymentType.CreditCard:
                // Do credit card calculations here
                break;                    
        }
    }
    else if (orderType == OrderType.Refund)
    {
        switch (paymentType)
        {
            case PaymentType.Cash:
                // Do cash calculations here
                break;
            case PaymentType.CreditCard:
                // Do credit card calculations here
                break;
            }
        }            
    }

由于

1 个答案:

答案 0 :(得分:0)

如果查看代码,您基本上想要的是让PaymentType处理两种订单。因此,如果您使用两种方法(销售和退款)将PaymentType实现为抽象类,那么您就拥有了策略模式的基础。

然后,您将实现两种具体的PaymentType(Cash和CreditCard),然后使用正在使用的付款方式配置合适的对象。

对于你的例子我真的认为战略是过度的。它也可能是错误的,因为策略通常用于配置全局默认值。在这里看起来你希望能够处理一堆交易而不管它们的实际具体类型。

在这里使用简单的多态与命令模式相结合可能会好得多,例如......

public interface Transaction {
  void perform();
}

public interface PaymentType {
  void sale();
  void refund();
}

public class Sale implements Transaction {
  private final PaymentType paymentType;

  public Sale(final PaymentType paymentType) {
    this.paymentType = paymentType;
  }

  public void perform() {
    paymentType.sale();
  }

}


public class Refund implements Transaction {
  private final PaymentType paymentType;

  public Refund(final PaymentType paymentType) {
    this.paymentType = paymentType;
  }

  public void perform() {
    paymentType.refund();
  }

}

现在你可以做到:

public void AddOrder(final Transaction transaction) {
  transaction.perform();
}

现在,您已将AddOrder与交易是销售还是退款,以及使用何种付款的任何知识脱钩。这样可以轻松添加新的交易(分期付款......)和新的付款方式(债务卡)。

相关问题