记录一次策略模式优化代码案例

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

策略模式优化案例

优化之前
在这里插入图片描述
优化之后
在这里插入图片描述
把原来的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);
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值