慕哥9229398
生成器设计模式可能会有所帮助。考虑以下示例public class StudentBuilder{ private String _name; private int _age = 14; // this has a default private String _motto = ""; // most students don't have one public StudentBuilder() { } public Student buildStudent() { return new Student(_name, _age, _motto); } public StudentBuilder name(String _name) { this._name = _name; return this; } public StudentBuilder age(int _age) { this._age = _age; return this; } public StudentBuilder motto(String _motto) { this._motto = _motto; return this; }}这让我们编写如下代码Student s1 = new StudentBuilder().name("Eli").buildStudent();Student s2 = new StudentBuilder() .name("Spicoli") .age(16) .motto("Aloha, Mr Hand") .buildStudent();如果我们忽略了必填字段(可能是必填名称),则可以让Student构造函数引发异常。而且它使我们可以使用默认/可选参数,而无需跟踪任何类型的参数顺序,因为这些调用的任何顺序都可以很好地工作。