Last active
July 8, 2021 06:11
-
-
Save BastiTee/84d1113710a991ed6775795a0771476b to your computer and use it in GitHub Desktop.
Generic and specialised data classes using builder pattern
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
public class GenericBuilderTest { | |
@Test | |
void test() { | |
final SpecialDataClass build = new SpecialBuilder() | |
// We want to call this in an arbitrary order! | |
.withCommonAttribute(-2) | |
.withSpecialAttribute(-1) | |
.withAnotherCommonAttribute(-3) | |
.build(); | |
assert build.specialAttribute == -1; | |
assert build.commonAttribute == -2; | |
assert build.anotherCommonAttribute == -3; | |
} | |
/** | |
* A generic data class that contains a generic builder to build its common attributes. | |
*/ | |
static abstract class GenericDataClass { | |
public int commonAttribute; | |
public int anotherCommonAttribute; | |
@SuppressWarnings("unchecked") | |
public static class GenericBuilder<A extends GenericDataClass, B extends GenericBuilder<?, ?>> { | |
protected A instance; | |
public GenericBuilder(Class<A> clazz) { | |
try { | |
instance = clazz.getDeclaredConstructor().newInstance(); | |
} catch (Exception e) { | |
throw new RuntimeException("Could not instantiate class " + clazz.getName()); | |
} | |
} | |
public B withCommonAttribute(int commonAttribute) { | |
instance.commonAttribute = commonAttribute; | |
return (B) this; | |
} | |
public B withAnotherCommonAttribute(int anotherCommonAttribute) { | |
instance.anotherCommonAttribute = anotherCommonAttribute; | |
return (B) this; | |
} | |
public A build() { | |
return instance; | |
} | |
} | |
} | |
/** | |
* A special data class that extends the generic builder with functions for each specialised attribute. | |
*/ | |
static class SpecialDataClass extends GenericDataClass { | |
private int specialAttribute; | |
public static class SpecialBuilder extends GenericBuilder<SpecialDataClass, SpecialBuilder> { | |
public SpecialBuilder() { | |
super(SpecialDataClass.class); | |
} | |
public SpecialBuilder withSpecialAttribute(int specialAttribute) { | |
instance.specialAttribute = specialAttribute; | |
return this; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment