使用策略模式 + Function优化if-else

由于Function接口的入参只支持一个参数,所以自定义一个MyFunction,支持多个参数,接口如下:

@FunctionalInterface
public interface MyFunction<T, R> {
    
    
    R apply(T... t);
}

下面就是如何使用了:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class)
public class MyFunctionTest {
    
    

    private static Map<String, MyFunction<Object, String>> map = new HashMap<>();

    @PostConstruct
    public void init(){
    
    
        map.put("A", MyFunctionTest::fun01);
        map.put("B", MyFunctionTest::fun02);
        map.put("C", MyFunctionTest::fun03);
    }

    private static String fun03(Object... o) {
    
    
        System.out.println("fun03=====>");
        for (Object o1 : o) {
    
    
            System.out.println(o1);
        }
        return "CCC";
    }

    private static String fun02(Object... o) {
    
    
        System.out.println("fun02=====>");
        for (Object o1 : o) {
    
    
            System.out.println(o1);
        }
        return "BBB";
    }

    private static String fun01(Object... o) {
    
    
        System.out.println("fun01=====>");
        for (Object o1 : o) {
    
    
            System.out.println(o1);
        }
        return "AAA";
    }

    @Test
    public void test(){
    
    
        String type = "A";
        // 以前的if-else
//        if(type.equals("A")){
    
    
//            fun01("a", 1);
//        }else if(type.equals("B")){
    
    
//            fun02("b", 2);
//        }else if(type.equals("C")){
    
    
//            fun03("c", 3);
//        }
        // 优化的if-else
        map.get(type).apply("a", 1);
    }
}

猜你喜欢

转载自blog.csdn.net/Linging_24/article/details/123305666