如何在 Java 中替换多个 if 语句

如何在 Java 中替换多个 if 语句

如何在 Java 中替换多个 if 语句

1. 工厂类

定义一个具有单个apply方法的Operation接口:

public interface Operation {
    int apply(int a, int b);
}

该方法将两个数字作为输入并返回结果。让我们定义两个执行加法的类:

public class Addition implements Operation {
    @Override
    public int apply(int a, int b) {
        return a + b;
    }
}


public class Reduce implements Operation {
    @Override
    public int apply(int a, int b) {
        return a - b;
    }
}

我们现在将实现一个工厂类,它根据给定的运算符返回Operation的实例:

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

public class OperatorFactory {
    static Map<String, Operation> operationMap = new HashMap<>();
    static {
        operationMap.put("add", new Addition());
        operationMap.put("reduce", new Reduce());
        // more operators
    }

    public static Optional<Operation> getOperation(String operator) {
        return Optional.ofNullable(operationMap.get(operator));
    }
}

现在,在Calculator类中,我们可以查询工厂以获取相关操作并应用于:

public class Calculator {

    @Test
    public void use(){
        System.out.println(calculateUsingFactory(1,2,"add"));
    }

    public int calculateUsingFactory(int a, int b, String operator) {
        Operation targetOperation = OperatorFactory
                .getOperation(operator)
                .orElseThrow(() -> new IllegalArgumentException("Invalid Operator"));
        return targetOperation.apply(a, b);
    }
}

2. 枚举的使用

除了使用Map,我们还可以使用Enum来标注特定的业务逻辑

我们将为每个Enum值定义方法并进行计算 需要导入google的 guava工具类

import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Getter;

import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;


@Getter
@AllArgsConstructor
public enum OperatorEnum {

    ADD(1) {
        @Override
        public int apply(int a, int b) {
            return a + b;
        }
    },

    MULTIPLY(2) {
        @Override
        public int apply(int a, int b) {
            return a * b;
        }
    },

    SUBTRACT(3) {
        @Override
        public int apply(int a, int b) {
            return a - b;
        }
    },

    DIVIDE(4) {
        @Override
        public int apply(int a, int b) {
            return a / b;
        }
    },

    MODULO(5) {
        @Override
        public int apply(int a, int b) {
            return a % b;
        }
    };

    public abstract int apply(int a, int b);

    private final Integer operator;

    private static final Map<Integer, OperatorEnum> LOOKUP = Maps.uniqueIndex(
            Arrays.asList(OperatorEnum.values()),
            OperatorEnum::getOperator
    );
    @Nullable
    public static OperatorEnum reversion(int status) {
        return LOOKUP.get(status);
    }
}

也可以使用实现

public interface Operator {
    int apply(int a, int b);
}
import com.google.common.collect.Maps;
import lombok.AllArgsConstructor;
import lombok.Getter;

import javax.annotation.Nullable;
import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

@Getter
@AllArgsConstructor
public enum OperatorEnum implements Operator{

    ADD(1) {
        @Override
        public int apply(int a, int b) {
            return a + b;
        }
    },

    MULTIPLY(2) {
        @Override
        public int apply(int a, int b) {
            return a * b;
        }
    },

    SUBTRACT(3) {
        @Override
        public int apply(int a, int b) {
            return a - b;
        }
    },

    DIVIDE(4) {
        @Override
        public int apply(int a, int b) {
            return a / b;
        }
    },

    MODULO(5) {
        @Override
        public int apply(int a, int b) {
            return a % b;
        }
    };


    private final Integer operator;

    private static final Map<Integer, OperatorEnum> LOOKUP = Maps.uniqueIndex(
            Arrays.asList(OperatorEnum.values()),
            OperatorEnum::getOperator
    );
    @Nullable
    public static OperatorEnum reversion(int status) {
        return LOOKUP.get(status);
    }
}

测试方法

public class Calculator {
    public int calculate(int a, int b, OperatorEnum operator) {
        return operator.apply(a, b);
    }


    @Test
    public void use(){
        System.out.println(calculate(1,2,OperatorEnum.reversion(1)));
    }


}

3. 命令模式

我们将首先定义我们的Command接口:

public interface Command {
    Integer execute();
}

接下来,让我们实现一个AddCommand:

public class AddCommand implements Command {
    private final int a;
    private final int b;

    public AddCommand(int a, int b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public Integer execute() {
        return a + b;
    }
}

最后,让我们在Calculator中引入一个接受并执行Command的新方法:

public class Calculator {
    public int calculate(Command command) {
        return command.execute();
    }

    @Test
    public void whenCalculateUsingCommand_thenReturnCorrectResult() {
        Calculator calculator = new Calculator();
        int result = calculator.calculate(new AddCommand(3, 7));
        assertEquals(10, result);
    }
}

4. Map+函数式接口

定义一个方法类

public class Operator {

    public static int add(int a,int b){
        return a+b;
    }

    public static int multiply(int a,int b){
        return a*b;
    }

    public static int subtract(int a,int b){
        return a-b;
    }
}
配置

配置一个实现工厂

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiFunction;


public class QueryGrantTypeService {
    // 两个参数使用 BiFunction 单个参数使用 Function 不需要返回值使用 Consumer消费函数 多个参数使用Function3 Function4
    private  static  Map<String, BiFunction<Integer,Integer,Integer>> grantTypeMap=new HashMap<>();
    // 静态代码块可以替换@PostConstruct
   static{
       grantTypeMap.put("add",(a,b)->Operator.add(a,b));
       grantTypeMap.put("subtract",(a,b)->Operator.subtract(a,b));
       grantTypeMap.put("multiply",(a,b)->Operator.multiply(a,b));
   }

    public Integer getResult(String resourceType,int a ,int b){
        BiFunction<Integer,Integer,Integer> result=grantTypeMap.get(resourceType);
            return result.apply(a,b);
    }
}

具体调用

public class Calculator {
    @Test
    public void use(){
        System.out.println(new QueryGrantTypeService().getResult("add",1,2));
    }
}

5. Vavr模式匹配

@Test
public void whenMatchworks_thenCorrect() {
    String arg="--help";
    Match(arg).of(
            Case($  (isIn("-h", "--help")), o -> run(this::displayHelp)),
            Case($(isIn("-v", "--version")), o -> run(this::displayVersion)),
            Case($(), o -> run(() -> {
                throw new IllegalArgumentException(arg);
            }))
    );
}
private void displayVersion(){
    System.out.println("--version");
}

private void displayHelp(){
    System.out.println("--help");
}