逛spring源码所发现的有趣的写法。
- 今日逛spring源码发现在DefaultListableBeanFactory类发现有两个方法写的挺有趣,利用函数式接口,让方法的执行逻辑交给方法调用者来决定,提高了代码的灵活性。特此记录,代码如下:
private void removeManualSingletonName(String beanName) {
updateManualSingletonNames(set -> set.remove(beanName), set -> set.contains(beanName));
}
/**
* Update the factory's internal set of manual singleton names.
* @param action the modification action
* @param condition a precondition for the modification action
* (if this condition does not apply, the action can be skipped)
*/
private void updateManualSingletonNames(Consumer<Set<String>> action, Predicate<Set<String>> condition) {
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {
if (condition.test(this.manualSingletonNames)) {
Set<String> 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;
/**
* @author : HY
* @version : V1.0
* @ClassName : MethodLambdaTest
* @Description:
* @date : 2022/1/18 16:04
*/
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<Set<String>> action, Predicate<Set<String>> condition) {
Set<String> updatedSingletons = new LinkedHashSet<>(set);
if (condition.test(updatedSingletons)) {
action.accept(updatedSingletons);
}
}
}
输出:
非常好用