top.doudou.core.builder.BaseBuilder Maven / Gradle / Ivy
package top.doudou.core.builder;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
/**
* @Description 通用的 Builder 模式构建器
* @Author 傻男人 <[email protected]>
* @Date 2021-04-01 17:28
* @Version V1.0
*/
public class BaseBuilder {
private final Supplier instantiator;
private List> modifiers = new ArrayList<>();
public BaseBuilder(Supplier instantiator) {
this.instantiator = instantiator;
}
public static BaseBuilder of(Supplier instantiator) {
return new BaseBuilder<>(instantiator);
}
public BaseBuilder with(Consumer1 consumer, P1 p1) {
Consumer c = instance -> consumer.accept(instance, p1);
modifiers.add(c);
return this;
}
public BaseBuilder with(Consumer2 consumer, P1 p1, P2 p2) {
Consumer c = instance -> consumer.accept(instance, p1, p2);
modifiers.add(c);
return this;
}
public BaseBuilder with(Consumer3 consumer, P1 p1, P2 p2, P3 p3) {
Consumer c = instance -> consumer.accept(instance, p1, p2, p3);
modifiers.add(c);
return this;
}
public T build() {
T value = instantiator.get();
modifiers.forEach(modifier -> modifier.accept(value));
modifiers.clear();
return value;
}
/**
* 1 参数 Consumer
*/
@FunctionalInterface
public interface Consumer1 {
void accept(T t, P1 p1);
}
/**
* 2 参数 Consumer
*/
@FunctionalInterface
public interface Consumer2 {
void accept(T t, P1 p1, P2 p2);
}
/**
* 3 参数 Consumer
*/
@FunctionalInterface
public interface Consumer3 {
void accept(T t, P1 p1, P2 p2, P3 p3);
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy