package com.hengtiansoft.common.util;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class BuildUtils<T> {
private final Supplier<T> instantiator;
private List<Consumer<T>> modifiers = new ArrayList<>();
public BuildUtils(Supplier<T> instant) {
this.instantiator = instant;
}
public static <T> BuildUtils<T> of(Supplier<T> instant) {
return new BuildUtils<>(instant);
}
public <P1> BuildUtils<T> with(Consumer1<T, P1> consumer, P1 p1) { // NOSONAR
Consumer<T> c = instance -> consumer.accept(instance, p1);
modifiers.add(c);
return this;
}
public <P1, P2> BuildUtils<T> with(Consumer2<T, P1, P2> consumer, P1 p1, P2 p2) { // NOSONAR
Consumer<T> c = instance -> consumer.accept(instance, p1, p2);
modifiers.add(c);
return this;
}
public <P1, P2, P3> BuildUtils<T> with(Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2, P3 p3) { // NOSONAR
Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3);
modifiers.add(c);
return this;
}
public <P1, P2, P3, P4> BuildUtils<T> with(Consumer4<T, P1, P2, P3, P4> consumer, // NOSONAR
P1 p1, P2 p2, P3 p3, P4 p4) { // NOSONAR
Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3, p4);
modifiers.add(c);
return this;
}
public <P1, P2, P3, P4, P5> BuildUtils<T> with(Consumer5<T, P1, P2, P3, P4, P5> consumer, // NOSONAR
P1 p1, P2 p2, P3 p3, P4 p4, P5 p5) { // NOSONAR
Consumer<T> c = instance -> consumer.accept(instance, p1, p2, p3, p4, p5);
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<T, P1> {
/**
* 接收参数方法
*
* @param t 对象
* @param p1 参数二
*/
void accept(T t, P1 p1);
}
/**
* 2 参数 Consumer
*/
@FunctionalInterface
public interface Consumer2<T, P1, P2> {
/**
* 接收参数方法
*
* @param t 对象
* @param p1 参数一
* @param p2 参数二
*/
void accept(T t, P1 p1, P2 p2);
}
/**
* 3 参数 Consumer
*/
@FunctionalInterface
public interface Consumer3<T, P1, P2, P3> {
/**
* 接收参数方法
*
* @param t 对象
* @param p1 参数一
* @param p2 参数二
* @param p3 参数三
*/
void accept(T t, P1 p1, P2 p2, P3 p3);
}
@FunctionalInterface
public interface Consumer4<T, P1, P2, P3, P4> {
/**
* 接收参数方法
*
* @param t 对象
* @param p1 参数一
* @param p2 参数二
* @param p3 参数三
* @param p4 参数四
*/
void accept(T t, P1 p1, P2 p2, P3 p3, P4 p4);
}
@FunctionalInterface
public interface Consumer5<T, P1, P2, P3, P4, P5> {
/**
* 接收参数方法
*
* @param t 对象
* @param p1 参数一
* @param p2 参数二
* @param p3 参数三
* @param p4 参数四
* @param p5 参数五
*/
void accept(T t, P1 p1, P2 p2, P3 p3, P4 p4, P5 p5);
}
}