对于下面的方法,最合适的模式是什么?我倾向于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;
}
}
}谢谢
发布于 2012-10-22 19:33:20
如果您查看您的代码,您基本上想要的是让PaymentType处理两种订单。因此,如果您将PaymentType实现为具有两个方法的抽象类-销售和退款-您就有了策略模式的基础。
然后,您将实现两种具体的PaymentType (Cash和CreditCard),然后使用所使用的支付类型配置一个合适的对象。
对于你的例子,我真的认为这个策略有点过头了。它也可能是错误的,因为Strategy通常用于配置全局默认值。在这里,您似乎希望能够处理一组事务,而不考虑它们的实际具体类型。
在这里,使用简单的多态结合命令模式可能会好得多,比如...
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与任何关于交易是销售还是退款以及使用哪种支付方式的知识解耦。这使得添加一种新的事务(分期付款...)变得很容易。和新的支付方式(预付卡)。
https://stackoverflow.com/questions/11175886
复制相似问题