让我们说我们需要在一个标志的基础上对多个类的多个方法进行一些逻辑更改,同时保持向后兼容性。
有两种方式..
1.在每个班级中重载每个方法。然后在调用者代码中以if-else梯形结束调用正确的方法。
2.制作一个通用界面和一个工厂。根据传递给工厂的标志返回任何一个对象。来电者不需要任何改变。在创建对象时只需要进行一点改动。仅为两种类型创建工厂是否合乎逻辑?
根据您的经验,您会选择哪种?如何在这两种方式之间做出决定?你可以建议任何更好的方法吗?
答案 0 :(得分:3)
逻辑变化表明建议战略模式的行为。这样可以避免更改现有方法签名。
但您仍然可以使用工厂集中创建处理逻辑的具体策略对象。
import java.util.Random;
public class App {
public static void main(String[] args) {
App app = new App();
app.calculateSomething(new Random().nextBoolean());
}
private void calculateSomething(boolean isUsingLegacyLogic) {
CalculationStrategyFactory factory = new CalculationStrategyFactory();
CalculationStrategy strategy = factory.getCalculationStrategy(isUsingLegacyLogic);
Calculator calculator = new Calculator(strategy);
calculator.calculate();
}
class Calculator {
CalculationStrategy calculationStrategy;
Calculator(CalculationStrategy calculationStrategy) {
this.calculationStrategy = calculationStrategy;
}
// ...
public double calculate() {
// original code
// ...
// System.out.println("Calculation steps were done in sequential order.");
// return 0;
return calculationStrategy.calculate(this);
}
}
private interface CalculationStrategy {
double calculate(Calculator c);
}
private class SequentialCalculationHandler implements CalculationStrategy {
public double calculate(Calculator c) {
// ...
System.out.println("Calculation steps were done in sequential order.");
return 0;
}
}
private class ParallelCalculationHandler implements CalculationStrategy {
public double calculate(Calculator c) {
// ...
System.out.println("Calculation steps were done in parralel.");
return 0;
}
}
private class CalculationStrategyFactory {
public CalculationStrategy getCalculationStrategy(boolean isUsingLegacyLogic) {
if (isUsingLegacyLogic || Runtime.getRuntime().availableProcessors() == 1) {
return new SequentialCalculationHandler();
}
return new ParallelCalculationHandler();
}
}
}