Skip to content

Commit

Permalink
Implemented builder from-function factories
Browse files Browse the repository at this point in the history
  • Loading branch information
lyubomyr-shaydariv committed Sep 25, 2024
1 parent 141df38 commit 31f4c08
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 10 deletions.
6 changes: 6 additions & 0 deletions src/main/java/lsh/ext/gson/IBuilder0.java
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ public interface IBuilder0<R> {

R build();

static <R> IBuilder0<R> of(
final Supplier<? extends R> build
) {
return build::get;
}

interface ILookup<R> {

Supplier<IBuilder0<R>> lookup(TypeToken<? super R> typeToken);
Expand Down
18 changes: 13 additions & 5 deletions src/main/java/lsh/ext/gson/IBuilder1.java
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import java.util.Collection;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
Expand All @@ -15,20 +16,27 @@ public interface IBuilder1<A1, R> {

R build();

static <E, C extends Collection<E>> IBuilder1<E, C> of(final C collection) {
static <A1, R> IBuilder1<A1, R> of(
final Consumer<? super A1> consume,
final Supplier<? extends R> build
) {
return new IBuilder1<>() {
@Override
public void accept(final E e) {
collection.add(e);
public void accept(final A1 a1) {
consume.accept(a1);
}

@Override
public C build() {
return collection;
public R build() {
return build.get();
}
};
}

static <E, C extends Collection<E>> IBuilder1<E, C> of(final C collection) {
return of(collection::add, () -> collection);
}

static <E, C extends Collection<E>> Supplier<IBuilder1<E, C>> from(final Supplier<? extends C> collectionFactory) {
return () -> of(collectionFactory.get());
}
Expand Down
17 changes: 12 additions & 5 deletions src/main/java/lsh/ext/gson/IBuilder2.java
Original file line number Diff line number Diff line change
Expand Up @@ -16,20 +16,27 @@ public interface IBuilder2<A1, A2, R> {

R build();

static <K, V, M extends Map<K, V>> IBuilder2<K, V, M> of(final M map) {
static <A1, A2, R> IBuilder2<A1, A2, R> of(
final BiConsumer<? super A1, ? super A2> consume,
final Supplier<? extends R> build
) {
return new IBuilder2<>() {
@Override
public void accept(final K k, final V v) {
map.put(k, v);
public void accept(final A1 a1, final A2 a2) {
consume.accept(a1, a2);
}

@Override
public M build() {
return map;
public R build() {
return build.get();
}
};
}

static <K, V, M extends Map<K, V>> IBuilder2<K, V, M> of(final M map) {
return of(map::put, () -> map);
}

static <K, V, M extends Map<K, V>> Supplier<IBuilder2<K, V, M>> from(final Supplier<? extends M> factory) {
return () -> of(factory.get());
}
Expand Down

0 comments on commit 31f4c08

Please sign in to comment.