策略模式优化案例
优化之前

优化之后

把原来的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);
}
}
文章展示了如何使用策略模式替换switch-case结构,通过函数式接口MyBiFunction实现方法的动态调用。在StrategyTest类中,创建了一个Map存储接口实现,通过init()方法初始化并绑定具体的方法。在main方法中,根据传入的键从Map中获取并执行相应的函数,实现了灵活的逻辑处理。
1363

被折叠的 条评论
为什么被折叠?



