前言
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public class Student { int id; int age; String name; String gender; String profession; List<String> awards;
public Student(int id, int age, String name, String gender, String profession, List<String> awards) { this.id = id; this.age = age; this.name = name; this.gender = gender; this.profession = profession; this.awards = awards; }
|
学生类的属性非常多,导致构造函数,也非常多,如果我们通过new的方式创建很容易填错参数位置。
1 2 3 4 5 6 7
| public class Main { public static void main(String[] args) { List<String> awards = Arrays.asList("LPL 春季赛冠军","上海Major冠军"); Student student = new Student(1, 18, "小明", "男", "计算机科学与技术", awards); System.out.println(student); } }
|
建造者模式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
| public class Student { int id; int age; String name; String gender; String profession; List<String> awards;
private Student(int id, int age, String name, String gender, String profession, List<String> awards) { this.id = id; this.age = age; this.name = name; this.gender = gender; this.profession = profession; this.awards = awards; }
public static StudentBuilder builder() { return new StudentBuilder(); }
public static class StudentBuilder { int id; int age; String name; String gender; String profession; List<String> awards;
public StudentBuilder id(int id) { this.id = id; return this; }
public StudentBuilder age(int age) { this.age = age; return this; }
public StudentBuilder name(String name) { this.name = name; return this; }
public StudentBuilder gender(String gender) { this.gender = gender; return this; }
public StudentBuilder profession(String profession) { this.profession = profession; return this; }
public StudentBuilder awards(List<String> awards) { this.awards = awards; return this; }
public Student build() { return new Student(id, age, name, gender, profession, awards); } } }
|
1 2 3 4 5 6 7 8
| public class Main { public static void main(String[] args) { Student.StudentBuilder builder = Student.builder(); List<String> awards = Arrays.asList("LPL 春季赛冠军", "上海Major冠军"); builder.id(1).name("John Doe").gender("Male").awards(awards).profession("").build(); } }
|
建造者模式提供了一种清晰、灵活且易于维护的方式来构建对象,尤其适用于具有多个参数和复杂构建逻辑的情况。