对此策略模式的维基百科示例进行了修改

时间:2018-03-15 09:30:10

标签: design-patterns software-design

Considering this java example for strategy pattern:

如果我们有新的客户类型,例如会员顾客也可以被指控忠诚积分。结算策略可能会在正常或欢乐时段发生变化,如下所示:

NormalStrategyForMemberCustomer{
    double getActPrice(double rawPrice, int loyaltyPoints){
        return Math.max(rawPrice - loyaltyPoints, 0);
    }
}

HappyHoursStrategyForMemberCustomer{
    double getActPrice(double rawPrice, int loyaltyPoints){
        return Math.max(rawPrice*0.5 - loyaltyPoints, 0);
    }
}

在这种情况下,我应该将上述方法创建为新策略,并将Customer类中的新类作为MemberCustomer继承并尝试拟合策略模式吗?

或者是否有另一种更适合的设计模式?

另外,我知道用忠诚度积分减去rawPrice的逻辑可以转移到最终的创建账单步骤,但我这样做是为了使它类似于我在工作场所遇到的问题。

1 个答案:

答案 0 :(得分:0)

我会尝试使用类型。如果我误解了这个问题,请纠正我。

private class Customer
{
    Strategy<StrategyParam> s;
}

private class MemberCustomer
{
    Strategy<LoyaltyStrategyParam> s;
}

private interface Strategy<T extends StrategyParam>
{
  double getActAmount(T param);
}

private class StrategyParam {
    double rawPrice;
}

private class LoyaltyStrategyParam extends StrategyParam {
    int loyaltyPoints;
}

private class MemberStrategy implements Strategy<StrategyParam>
{
    double getActAmount(StrategyParam param);
}

private class HappyHourMemberStrategy implements Strategy<LoyaltyStrategyParam>
{
    double getActAmount(LoyaltyStrategyParam param);
}