从实习公司获取到的链式new对象的代码
import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class BuilderUtil<T> {
private final Supplier<T> instantiator;
private List<Consumer<T>> modifiers = new ArrayList();
public BuilderUtil(Supplier<T> instantiator) {
this.instantiator = instantiator;
}
public static <T> BuilderUtil<T> of(Supplier<T> instantiator) {
return new BuilderUtil(instantiator);
}
public <P1> BuilderUtil<T> with(BuilderUtil.Consumer1<T, P1> consumer, P1 p1) {
Consumer<T> c = (instance) -> {
consumer.accept(instance, p1);
};
this.modifiers.add(c);
return this;
}
public <P1, P2> BuilderUtil<T> with(BuilderUtil.Consumer2<T, P1, P2> consumer, P1 p1, P2 p2) {
Consumer<T> c = (instance) -> {
consumer.accept(instance, p1, p2);
};
this.modifiers.add(c);
return this;
}
public <P1, P2, P3> BuilderUtil<T> with(BuilderUtil.Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2, P3 p3) {
Consumer<T> c = (instance) -> {
consumer.accept(instance, p1, p2, p3);
};
this.modifiers.add(c);
return this;
}
public T build() {
T value = this.instantiator.get();
this.modifiers.forEach((modifier) -> {
modifier.accept(value);
});
this.modifiers.clear();
return value;
}
@FunctionalInterface
public interface Consumer3<T, P1, P2, P3> {
void accept(T var1, P1 var2, P2 var3, P3 var4);
}
@FunctionalInterface
public interface Consumer2<T, P1, P2> {
void accept(T var1, P1 var2, P2 var3);
}
@FunctionalInterface
public interface Consumer1<T, P1> {
void accept(T var1, P1 var2);
}
}
|