系列文章目录
Java 建造者 Builder.of
一、示例实体
代码如下(示例):
/**
* @descriptions: BidResp
* @author:
* @date: 2024/2/29 15:07
* @version: 1.0
*/
@Data
public class RespTest implements Serializable {
private static final long serialVersionUID = 1L;
private String name;
private String field;
private String type;
private String value;
private String status;
}
二、构造工具
1.引入库
代码如下(示例):
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
2.工具类
代码如下(示例):
public class Builder<T> {
private final Supplier<T> instantiate;
private final List<Consumer<T>> setterList = new ArrayList<>();
private Builder(Supplier<T> instantiation) {
this.instantiate = instantiation;
}
public static <T> Builder<T> of(Supplier<T> instantiator){
return new Builder<>(instantiator);
}
public <P> Builder<T> with(IOneParamSetter<T, P> setter, P p) {
Consumer<T> c = instance -> setter.accept(instance, p);
setterList.add(c);
return this;
}
public <P0, P1> Builder<T> with(ITwoParamSetter<T, P0, P1> setter, P0 p0, P1 p1) {
Consumer<T> c = instance -> setter.accept(instance, p0, p1);
setterList.add(c);
return this;
}
public T build() {
T value = instantiate.get();
setterList.forEach(setter -> setter.accept(value));
setterList.clear();
return value;
}
@FunctionalInterface
public interface IOneParamSetter<T, P> {
void accept(T t, P p);
}
@FunctionalInterface
public interface ITwoParamSetter<T, P0, P1> {
void accept(T t, P0 p0, P1 p1);
}
}
调用代码如下(示例):
/**
* @descriptions:
* @author: kangsx184@tydic.com
* @date: 2024/4/18 10:24
* @version: 1.0
*/
public class test {
public static void main(String[] args) {
RespTest resp = Builder.of(RespTest ::new)
.with(RespTest ::setField,"animal")
.with(RespTest ::setName,"cat")
.with(RespTest ::setType,"01")
.with(RespTest ::setValue,"1000")
.with(RespTest ::setStatus,"1")
.build();
System.out.println("RespTest 对象:" + resp );
}
}