fork download
  1. class Example {
  2. public static void main(String[] args) {
  3. Thingy t = new Thingy.Builder()
  4. .withState1("one")
  5. .withState2("two")
  6. .withState3("three")
  7. .build();
  8. System.out.println(t.getState());
  9. }
  10. }
  11. class Thingy {
  12. private String state;
  13.  
  14. private Thingy(String s1, String s2, String s3) {
  15. this.state = s1 + "/" + s2 + "/" + s3;
  16. }
  17.  
  18. public String getState() {
  19. return this.state;
  20. }
  21.  
  22. public static class Builder {
  23. private String state1 = null;
  24. private String state2 = null;
  25. private String state3 = null;
  26.  
  27. public Builder withState1(String s1) {
  28. this.state1 = s1;
  29. return this;
  30. }
  31.  
  32. public Builder withState2(String s2) {
  33. this.state2 = s2;
  34. return this;
  35. }
  36.  
  37. public Builder withState3(String s3) {
  38. this.state3 = s3;
  39. return this;
  40. }
  41.  
  42. public Thingy build() {
  43. if (this.state1 == null) {
  44. throw new IllegalStateException("state1 is required");
  45. }
  46. if (this.state2 == null) {
  47. throw new IllegalStateException("state2 is required");
  48. }
  49. if (this.state3 == null) {
  50. throw new IllegalStateException("state3 is required");
  51. }
  52. return new Thingy(this.state1, this.state2, this.state3);
  53. }
  54. }
  55. }
Success #stdin #stdout 0.1s 320512KB
stdin
Standard input is empty
stdout
one/two/three