策略模式优化案例
优化之前
优化之后
把原来的switch case 用接口方式实现
bean 注入采用map方式 key为 实现类的名称,value为实现类的bean,在所有bean注入之后执行init() 方法,将具体的实现模板放到 map中
函数式接口+策略模式的案例
自定义一个函数接口 接收三个参数,返回一个参数
@FunctionalInterface
public interface MyBiFunction<T, U,X, R> {
R run(T t, U u ,X x);
}
public class StrategyTest {
private static final Map<String, MyBiFunction<ObjectNode, Long, StringBuffer, String>> map = new HashMap<>(16);
public static void init() {
map.put("type", StrategyTest::method1);
map.put("type1", StrategyTest::method2);
}
public static String method1(ObjectNode node1, Long uid, StringBuffer buffer) {
System.out.println("接收到的数据: " + node1);
System.out.println(uid);
System.out.println(buffer);
return "方法一";
}
public static String method2(ObjectNode node1, Long uid, StringBuffer buffer) {
System.out.println("接收到的数据: " + node1);
System.out.println(uid);
System.out.println(buffer);
return "方法二";
}
public static void main(String[] args) {
init();
MyBiFunction<ObjectNode, Long, StringBuffer, String> function = map.get("type1");
ObjectNode obj = new ObjectMapper().createObjectNode();
obj.put("age", "11");
obj.put("name", "ooo");
String apply = function.run(obj, 10L, new StringBuffer("kk"));
System.out.println("相应结果:" + apply);
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)