概述
问题描述:
之前用策略模式实现的内容组长说可读性较差(其实也不是可读性差,就是组长习惯用ctrl点进去看哪里调用了这个方法),于是乎想着怎么能优化下代码,为后来的人的维护与阅读带来便捷。以下是写的Demo,给大家提供一个思路
直接上代码。:
@Override
public class MethodDemo {
public static Integer method1(String name){
System.out.println("method1" + name);
return null;
}
public static Integer method2(String name){
System.out.println("method2" + name);
return null;
}
public static Integer method3(String name){
System.out.println("method3" + name);
return null;
}
public static Integer method4(String name){
System.out.println("method4" + name);
return null;
}
}
先定义一个方法类,里面可以放入具体逻辑。
public class FunctionUtil {
// 策略模式测试
static Map<String, Function<String, Integer>> calculateMethodMap = new HashMap<>();
static {
MethodDemo methodDemo = new MethodDemo();
System.out.println("创建了");
Class methodDemoClass = methodDemo.getClass();
Method[] methods = methodDemoClass.getMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
calculateMethodMap.put(method.getName(), name -> {
try {
return (Integer)method.invoke(methodDemo, name);
} catch (IllegalAccessException e) {
return null;
} catch (InvocationTargetException e) {
return null;
}
});
}
}
}
这个类是用来调用方法的类,需要在map的key处传入所要调用的方法。PS:个人这里的异常处理有瑕疵,仅作为演示。
public class FunctionUtilTest {
public static void main(String[] args) {
//如图展示,调用map的get方法获得Funcation
//再调用Funcation的apply方法传入参数
FunctionUtil.calculateMethodMap.get("method1").apply("哈哈哈");
FunctionUtil.calculateMethodMap.get("method2").apply("呵呵呵");
FunctionUtil.calculateMethodMap.get("method4").apply("喔喔喔");
FunctionUtil.calculateMethodMap.get("method3").apply("咯咯咯");
}
}
输出结果:
结言:
以上就是map搭配Function的实现过程,如果调用得方法不需要传入参数可以在Map的value中用Consumer作为value,只是提供多一种思路,但是写完之后感觉可读性还是一般。。多多修炼吧
最后
以上就是笑点低寒风为你收集整理的使用Map搭配Function实现策略模式问题描述:结言:的全部内容,希望文章能够帮你解决使用Map搭配Function实现策略模式问题描述:结言:所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复