Skip to content

Instantly share code, notes, and snippets.

@lazywithclass
Created December 22, 2011 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lazywithclass/1511267 to your computer and use it in GitHub Desktop.
Save lazywithclass/1511267 to your computer and use it in GitHub Desktop.
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