Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Builder pattern with compile time check
public class Complex {
private Complex() {}
public static void main(String[] args) {
new ComplexBuilder()
.setFirst("first")
.setSecond("second")
.setThird( "third" )
.build();
}
private String m_first;
private String m_second;
private String m_third;
public static class ComplexBuilder {
private Complex m_complex;
public ComplexBuilder() {
m_complex = new Complex();
}
public Builder2 setFirst( String first ) {
m_complex.m_first = first;
return new Builder2();
}
public class Builder2 {
private Builder2() {}
Builder3 setSecond( String second ) {
m_complex.m_second = second;
return new Builder3();
}
}
public class Builder3 {
private Builder3() {}
Builder4 setThird( String third ) {
m_complex.m_third = third;
return new Builder4();
}
}
public class Builder4 {
private Builder4() {}
Complex build() {
return m_complex;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.