Skip to content

Commit

Permalink
Added more factory methods to the builders
Browse files Browse the repository at this point in the history
  • Loading branch information
lyubomyr-shaydariv committed Sep 25, 2024
1 parent e8a8fb8 commit 29a4038
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/main/java/lsh/ext/gson/IBuilder1.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,43 @@ public R build() {
};
}

static <A1, R, AUX> IBuilder1<A1, R> of(
final Supplier<? extends AUX> createAux,
final BiConsumer<? super A1, ? super AUX> consume,
final Function<? super AUX, ? extends R> build
) {
return new IBuilder1<>() {
private boolean isInitialized;
@Nullable
private AUX aux;

@Override
public void accept(final A1 a1) {
consume.accept(a1, createOrGet());
}

@Override
public R build() {
return build.apply(createOrGet());
}

private AUX createOrGet() {
if ( !isInitialized ) {
aux = createAux.get();
isInitialized = true;
}
return aux;
}
};
}

static <A1, R> IBuilder1<A1, R> of(
final Supplier<? extends R> createResult,
final BiConsumer<? super A1, ? super R> consume
) {
return of(createResult, consume, Function.identity());
}

static <A1, R, CA> IBuilder1<A1, R> of(final Collector<? super A1, CA, ? extends R> collector) {
return new IBuilder1<>() {
private final Supplier<? extends CA> supplier = collector.supplier();
Expand Down
37 changes: 37 additions & 0 deletions src/main/java/lsh/ext/gson/IBuilder2.java
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,43 @@ public R build() {
};
}

static <A1, A2, R, AUX> IBuilder2<A1, A2, R> of(
final Supplier<? extends AUX> createAux,
final TriConsumer<? super A1, ? super A2, ? super AUX> consume,
final Function<? super AUX, ? extends R> build
) {
return new IBuilder2<>() {
private boolean isInitialized;
@Nullable
private AUX aux;

@Override
public void accept(final A1 a1, final A2 a2) {
consume.accept(a1, a2, createOrGet());
}

@Override
public R build() {
return build.apply(createOrGet());
}

private AUX createOrGet() {
if ( !isInitialized ) {
aux = createAux.get();
isInitialized = true;
}
return aux;
}
};
}

static <A1, A2, R> IBuilder2<A1, A2, R> of(
final Supplier<? extends R> createResult,
final TriConsumer<? super A1, ? super A2, ? super R> consume
) {
return of(createResult, consume, Function.identity());
}

static <A1, A2, R, CT, CA> IBuilder2<A1, A2, R> of(
final Collector<? super CT, CA, ? extends R> collector,
final BiFunction<? super A1, ? super A2, ? extends CT> toElementType
Expand Down

0 comments on commit 29a4038

Please sign in to comment.