code_junkie

Managing constructors with many parameters in Java 1.4

Nov 11th, 2011
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. public class StudentBuilder
  2. {
  3. private String _name;
  4. private int _age = 14; // this has a default
  5. private String _motto = ""; // most students don't have one
  6.  
  7. public StudentBuilder() { }
  8.  
  9. public Student buildStudent()
  10. {
  11. return new Student(_name, _age, _motto);
  12. }
  13.  
  14. public StudentBuilder name(String _name)
  15. {
  16. this._name = _name;
  17. return this;
  18. }
  19.  
  20. public StudentBuilder age(int _age)
  21. {
  22. this._age = age;
  23. return this;
  24. }
  25.  
  26. public StudentBuilder motto(String _motto)
  27. {
  28. this._motto = _motto;
  29. return this;
  30. }
  31. }
  32.  
  33. Student s1 = new StudentBuilder().name("Eli").buildStudent();
  34. Student s2 = new StudentBuilder()
  35. .name("Spicoli")
  36. .age(16)
  37. .motto("Aloha, Mr Hand")
  38. .buildStudent();
  39.  
  40. MyClass(String house, String street, String town, String postcode, String country, int foo, double bar) {
  41. super(String house, String street, String town, String postcode, String country);
  42. this.foo = foo;
  43. this.bar = bar;
  44.  
  45. MyClass(Address homeAddress, int foo, double bar) {
  46. super(homeAddress);
  47. this.foo = foo;
  48. this.bar = bar;
  49. }
  50.  
  51. MyObject obj = new MyObjectBuilder().setXxx(myXxx)
  52. .setYyy(myYyy)
  53. .setZzz(myZzz)
  54. // ... etc.
  55. .build();
Add Comment
Please, Sign In to add comment