今日逛spring源码发现在DefaultListableBeanFactory类发现有两个方法写的挺有趣,利用函数式接口,让方法的执行逻辑交给方法调用者来决定,提高了代码的灵活性。特此记录,代码如下:
private void removeManualSingletonName(String beanName) { updateManualSingletonNames(set -> set.remove(beanName), set -> set.contains(beanName)); } private void updateManualSingletonNames(Consumer> action, Predicate > condition) { if (hasBeanCreationStarted()) { // Cannot modify startup-time collection elements anymore (for stable iteration) synchronized (this.beanDefinitionMap) { if (condition.test(this.manualSingletonNames)) { Set updatedSingletons = new linkedHashSet<>(this.manualSingletonNames); action.accept(updatedSingletons); this.manualSingletonNames = updatedSingletons; } } } else { // Still in startup registration phase if (condition.test(this.manualSingletonNames)) { action.accept(this.manualSingletonNames); } } }
以下是自己模拟的代码:
package lambda.test; import java.util.HashSet; import java.util.linkedHashSet; import java.util.Set; import java.util.function.Consumer; import java.util.function.Predicate; public class MethodLambdaTest { private static Set set = new HashSet(); static{ set.add("1"); set.add("2"); } public static void main(String[] args) { MethodLambdaTest methodLambdaTest = new MethodLambdaTest(); methodLambdaTest.doSome(System.out::println, b -> b.contains("1")); } public void doSome(Consumer> action, Predicate > condition) { Set updatedSingletons = new linkedHashSet<>(set); if (condition.test(updatedSingletons)) { action.accept(updatedSingletons); } } }
输出:
非常好用
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)