T - 构建对象类型public class GenericBuilder<T> extends Object implements Builder<T>
通用Builder
参考: 一看就会的java8通用Builder使用方法如下:
Box box = GenericBuilder
.of(Box::new)
.with(Box::setId, 1024L)
.with(Box::setTitle, "Hello World!")
.with(Box::setLength, 9)
.with(Box::setWidth, 8)
.with(Box::setHeight, 7)
.build();
我们也可以对已创建的对象进行修改:
Box boxModified = GenericBuilder
.of(() -> box)
.with(Box::setTitle, "Hello Friend!")
.with(Box::setLength, 3)
.with(Box::setWidth, 4)
.with(Box::setHeight, 5)
.build();
我们还可以对这样调用有参构造,这对于创建一些在有参构造中包含初始化函数的对象是有意义的:
Box box1 = GenericBuilder
.of(Box::new, 2048L, "Hello Partner!", 222, 333, 444)
.with(Box::alis)
.build();
还可能这样构建Map对象:
HashMap<String, String> colorMap = GenericBuilder
.of(HashMap<String,String>::new)
.with(Map::put, "red", "#FF0000")
.with(Map::put, "yellow", "#FFFF00")
.with(Map::put, "blue", "#0000FF")
.build();
注意:本工具类支持调用的构造方法的参数数量不超过5个,一般方法的参数数量不超过2个,更多的参数不利于阅读和维护。
| Constructor and Description |
|---|
GenericBuilder(Supplier<T> instant)
构造
|
| Modifier and Type | Method and Description |
|---|---|
T |
build()
构建
|
static <T> GenericBuilder<T> |
of(Supplier<T> instant)
通过Supplier创建GenericBuilder
|
<P1> GenericBuilder<T> |
with(BiConsumer<T,P1> consumer,
P1 p1)
调用1参数方法
|
GenericBuilder<T> |
with(Consumer<T> consumer)
调用无参数方法
|
<P1,P2> GenericBuilder<T> |
with(SerConsumer3<T,P1,P2> consumer,
P1 p1,
P2 p2)
调用2参数方法
|
public static <T> GenericBuilder<T> of(Supplier<T> instant)
T - 目标类型instant - 实例化器public GenericBuilder<T> with(Consumer<T> consumer)
consumer - 无参数Consumerpublic <P1> GenericBuilder<T> with(BiConsumer<T,P1> consumer, P1 p1)
P1 - 参数一类型consumer - 1参数Consumerp1 - 参数一public <P1,P2> GenericBuilder<T> with(SerConsumer3<T,P1,P2> consumer, P1 p1, P2 p2)
P1 - 参数一类型P2 - 参数二类型consumer - 2参数Consumerp1 - 参数一p2 - 参数二Copyright © 2025. All rights reserved.