1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| public class Builder<T> { private final Supplier<T> instantiator; private List<Consumer<T>> modifiers = new ArrayList<>(); public Builder(Supplier<T> instantiator) { this.instantiator = instantiator; } public static <T> Builder<T> of(Supplier<T> instantiator) { return new Builder<>(instantiator); } public <P1> Builder<T> with(Consumer1<T, P1> consumer, P1 p1) { Consumer<T> c = instance -> consumer.accept(instance, p1); modifiers.add(c); return this; } public <P1, P2> Builder<T> with(Consumer2<T, P1, P2> consumer, P1 p1, P2 p2) { Consumer<T> c = instance -> consumer.accept(instance, p1, p2); modifiers.add(c); return this; } public <P1, P2, P3> Builder<T> with(Consumer3<T, P1, P2, P3> consumer, P1 p1, P2 p2, P3 p3) { Consumer<T> 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; }
@FunctionalInterface public interface Consumer1<T, P1> { void accept(T t, P1 p1); }
@FunctionalInterface public interface Consumer2<T, P1, P2> { void accept(T t, P1 p1, P2 p2); }
@FunctionalInterface public interface Consumer3<T, P1, P2, P3> { void accept(T t, P1 p1, P2 p2, P3 p3); } }
|