lundi 18 janvier 2021

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

I want to get rid of Switch with different operations in the code. Can this be done using the Strategy pattern in this case (or is there another way?):

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: the code doesn't work, because I don't understand how to implement the Strategy interface without removing the pow method from the Sum class.

Aucun commentaire:

Enregistrer un commentaire