Pattern Strategy vs Switch OR 如何处理大量不同的操作

Pattern Strategy vs Switch OR How to handle a large number of different operations

我想在代码中去掉不同操作的Switch。在这种情况下可以使用策略模式来完成吗(或者有其他方法吗?):

public interface Strategy {
    BigDecimal minus(BigDecimal a, BigDecimal b);
    BigDecimal sum(BigDecimal a, BigDecimal b);
    BigDecimal pow(BigDecimal a, int n);
}

public class Minus implements Strategy {
    public BigDecimal minus(BigDecimal a, BigDecimal b) {
        return a.subtract(b);
    }
}

public class Sum implements Strategy{
    public BigDecimal sum(BigDecimal a, BigDecimal b) {
        return a.add(b);
    }

    public BigDecimal pow(BigDecimal a, int n) {
        return a.pow(n);
    }
}

public class Calc {
    private Strategy strategy;
    private BigDecimal a;
    private BigDecimal b;
    private int n;

    public Calc(Strategy strategy, BigDecimal a, BigDecimal b, int n) {
        this.strategy = strategy;
        this.a = a;
        this.b = b;
        this.n = n;
    }

    public void calculate(String operation) {
        switch (operation) {
            case "SUM":
                strategy.sum(a, b);
                break;
            case "POW":
                strategy.pow(a, n);
                break;
            case "MINUS":
                strategy.minus(a, b);
        }
    }
}

ps:代码不起作用,因为我不明白如何在不从 Sum class.

中删除 pow 方法的情况下实现 Strategy 接口

你对策略模式有什么误解。简单地说,通过实施它,您有 classes,每个都提供了一种行为的特殊表现形式。你比 select 从所有这些可能的表现中,哪一个用于你的特殊情况。 您的界面策略 - 让我们更好地将其命名为 TwoParamOperation 然后看起来像这样:

public interface TwoParamOperation {
    BigDecimal compute(BigDecimal operand1, BigDecimal operand2);
}

您的实际实现可能是:

public class Minus implements TwoParamOperation{
    @Override
    public BigDecimal compute(BigDecimal operand1, BigDecimal operand2) {
        return operand1.subtract(operand2);
    }
}

public class Pow implements TwoParamOperation{
    @Override
    public BigDecimal compute(BigDecimal operand1, BigDecimal operand2) {
        return operand1.pow(operand2.intValue());
    }
}

然后你必须从这些策略中实施一种机制 select。您可以简单地将操作名称作为键并将策略实例作为值的映射:

public class 计算 {

private Map<String,TwoParamOperation> operations = new HashMap<>();

public Calc(){
    add("MINUS", new Minus());
    add("POW", new Pow());
}

public void add(String opName,TwoParamOperation operation){
    operations.put(opName,operation);
}
    
    public Optional<BigDecimal> calculate(String opName, BigDecimal operand1, BigDecimal operand2){
    TwoParamOperation operation = operations.get(opName);
    if (operation!= null){
        return Optional.of(operation.compute(operand1,operand2));
    }
    return Optional.empty();
}

}

这样您甚至可以添加新的操作。删除取决于你.. 通过调用

Calc calc = new Calc();

BigDecimal x=calc.calculate("MINUS",BigDecimal.valueOf(2.3),BigDecimal.valueOf(42)).orElseThrow();

如果实施了这样的操作,您将获得对两个参数的 selected 操作的结果。

如果您需要使用其他参数或结果类型进行操作,您可以将它们添加为其他接口的额外映射。