mirror of
https://gitee.com/dromara/hutool.git
synced 2025-05-07 22:27:59 +08:00
feat(LazyFunLoader): 增加静态工厂方法
This commit is contained in:
parent
ca5732e6df
commit
2f5a68c8a5
@ -24,6 +24,17 @@ public class LazyFunLoader<T> extends LazyLoader<T> {
|
|||||||
*/
|
*/
|
||||||
private Supplier<T> supplier;
|
private Supplier<T> supplier;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 静态工厂方法,提供语义性与编码便利性
|
||||||
|
* @param supplier 用于生成对象的函数
|
||||||
|
* @param <T> 对象类型
|
||||||
|
* @return 函数式懒加载加载器对象
|
||||||
|
*/
|
||||||
|
public static <T> LazyFunLoader<T> onLoad(final Supplier<T> supplier) {
|
||||||
|
Assert.notNull(supplier, "supplier");
|
||||||
|
return new LazyFunLoader<>(supplier);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 构造
|
* 构造
|
||||||
*
|
*
|
||||||
|
@ -42,4 +42,32 @@ public class LazyFunLoaderTest {
|
|||||||
|
|
||||||
Assert.assertFalse(loader.isInitialize());
|
Assert.assertFalse(loader.isInitialize());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testOnLoadStaticFactoryMethod1() {
|
||||||
|
|
||||||
|
LazyFunLoader<BigObject> loader = LazyFunLoader.onLoad(BigObject::new);
|
||||||
|
|
||||||
|
Assert.assertNotNull(loader.get());
|
||||||
|
Assert.assertTrue(loader.isInitialize());
|
||||||
|
|
||||||
|
// 对于某些对象,在程序关闭时,需要进行销毁操作
|
||||||
|
loader.ifInitialized(BigObject::destroy);
|
||||||
|
|
||||||
|
Assert.assertTrue(loader.get().isDestroy);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testOnLoadStaticFactoryMethod2() {
|
||||||
|
|
||||||
|
LazyFunLoader<BigObject> loader = LazyFunLoader.onLoad(BigObject::new);
|
||||||
|
|
||||||
|
// 若从未使用,则可以避免不必要的初始化
|
||||||
|
loader.ifInitialized(it -> {
|
||||||
|
|
||||||
|
Assert.fail();
|
||||||
|
it.destroy();
|
||||||
|
});
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user