Created
December 22, 2011 18:13
-
-
Save lazywithclass/1511267 to your computer and use it in GitHub Desktop.
Builder pattern with compile time check
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 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