【421、优化 if-else 方法】

85 阅读1分钟

以下是一些在 Java 中优化 if-else 的代码示例:

  1. 使用多态
abstract class Operation {
    public abstract int operate(int x, int y);
}

class AddOperation extends Operation {
    public int operate(int x, int y) {
        return x + y;
    }
}

class SubtractOperation extends Operation {
    public int operate(int x, int y) {
        return x - y;
    }
}

class Calculator {
    public static void main(String[] args) {
        Operation op = new AddOperation(); // 根据实际需求创建不同的操作对象
        int result = op.operate(1, 2); // 自动调用相应的操作
        System.out.println(result);
    }
}
  1. 使用状态模式
interface State {
    void handle();
}

class AState implements State {
    public void handle() {
        System.out.println("A state");
    }
}

class BState implements State {
    public void handle() {
        System.out.println("B state");
    }
}

class Context {
    private State state;
    
    public Context(State state) {
        this.state = state;
    }
    
    public void setState(State state) {
        this.state = state;
    }
    
    public void handle() {
        state.handle();
    }
}

class StatePatternDemo {
    public static void main(String[] args) {
        Context context = new Context(new AState()); // 初始状态为 AState
        context.handle();
        context.setState(new BState()); // 改变状态为 BState
        context.handle();
    }
}
  1. 使用数据结构
interface Operation {
    int operate(int x, int y);
}

class AddOperation implements Operation {
    public int operate(int x, int y) {
        return x + y;
    }
}

class SubtractOperation implements Operation {
    public int operate(int x, int y) {
        return x - y;
    }
}

class Calculator {
    private static final Map<String, Operation> operations = new HashMap<>();
    static {
        operations.put("+", new AddOperation());
        operations.put("-", new SubtractOperation());
    }
    
    public static void main(String[] args) {
        String operator = "+"; // 根据实际需求选择不同的操作符
        int result = operations.get(operator).operate(1, 2); // 根据操作符从映射表中获取相应的操作
        System.out.println(result);
    }
}

总之,在 Java 中优化 if-else 的关键是要理解需求,选择合适的技术和策略,并保持代码简洁、可读、易于扩展和维护。