Last active
January 16, 2024 19:11
-
-
Save OndroMih/1acc4f23cd7b229ccb5e3a783039df0a to your computer and use it in GitHub Desktop.
Universal functional builder for Java objects
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.function.BiConsumer; | |
import java.util.function.Consumer; | |
import java.util.function.Supplier; | |
/** | |
* | |
* @author Ondro Mihalyi | |
*/ | |
public class FunctionalBuilder<PRODUCT> { | |
private final PRODUCT product; | |
public FunctionalBuilder(Supplier<PRODUCT> initialSupplier) { | |
this.product = initialSupplier.get(); | |
} | |
public static <STATIC_PRODUCT> FunctionalBuilder<STATIC_PRODUCT> from(Supplier<STATIC_PRODUCT> initialSupplier) { | |
return new FunctionalBuilder<>(initialSupplier); | |
} | |
public <VALUE> FunctionalBuilder<PRODUCT> with(BiConsumer<PRODUCT, VALUE> setter, VALUE value) { | |
setter.accept(product, value); | |
return this; | |
} | |
public static <STATIC_PRODUCT> STATIC_PRODUCT build(Supplier<STATIC_PRODUCT> initialSupplier, Consumer<STATIC_PRODUCT>... setters) { | |
STATIC_PRODUCT product = initialSupplier.get(); | |
for (Consumer<STATIC_PRODUCT> setter : setters) { | |
setter.accept(product); | |
} | |
return product; | |
} | |
public PRODUCT build() { | |
return product; | |
} | |
public static void main(String[] args) { | |
// Pojo functionalBuilder = buildByFunctionalBuilder(); | |
Pojo functionalBuilder = buildByStaticFunctionalBuilder(); | |
if (!functionalBuilder.getName().equals("my pojo")) { | |
throw new AssertionError("name doesn't equal 'my pojo'"); | |
} | |
if (functionalBuilder.getSize() != 10) { | |
throw new AssertionError("size doesn't equal '10'"); | |
} | |
} | |
private static Pojo buildByFunctionalBuilder() { | |
return FunctionalBuilder.from(Pojo::new) | |
.with(Pojo::setName, "my pojo") | |
.with(Pojo::setSize, 10) | |
.build(); | |
} | |
private static Pojo buildByStaticFunctionalBuilder() { | |
return FunctionalBuilder.build( | |
Pojo::new, | |
o -> o.setName("my pojo"), | |
o -> o.setSize(10) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment