Skip to content

Instantly share code, notes, and snippets.

@jdigger
Last active August 29, 2015 14:12
Show Gist options
  • Save jdigger/eba739548b3b9a24f81b to your computer and use it in GitHub Desktop.
Save jdigger/eba739548b3b9a24f81b to your computer and use it in GitHub Desktop.
Class builder example
import javax.annotation.Nonnull;
/**
* @see #withValue1(String)
*/
public class ComplexValueClass {
private final String value1;
private final String value2;
private final String value3;
private ComplexValueClass(String value1, String value2, String value3) {
if (value1 == null) throw new IllegalArgumentException("value1 == null");
if (value2 == null) throw new IllegalArgumentException("value2 == null");
if (value3 == null) throw new IllegalArgumentException("value3 == null");
this.value1 = value1;
this.value2 = value2;
this.value3 = value3;
}
/**
* Example:<pre>
* ComplexValueClass complexClass = ComplexValueClass.withValue1("a").
* andValue2("b").
* andValue3("c").
* build();
* </pre>
*/
public static Builder withValue1(@Nonnull String val) {
return new Builder(val);
}
/**
* Not meant to be used directly.
* @see ComplexValueClass#withValue1(String)
*/
public static class Builder {
private final String value1;
private Builder(String val) {
this.value1 = val;
}
public Builder2 andValue2(@Nonnull String val) {
return new Builder2(val);
}
public class Builder2 {
private final String value2;
private Builder2(String val) {
this.value2 = val;
}
public Builder3 andValue3(@Nonnull String val) {
return new Factory3(val);
}
public class Builder3 {
private final String value3;
private Builder3(String val) {
this.value3 = val;
}
public ComplexValueClass build() {
return new ComplexValueClass(value1, value2, value3);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment