外观往往和事物的本身完全不符,世人都容易为表面的装饰所欺骗。——《威尼斯商人》
这两天开发中用到了建造者模式,写起来感觉挺爽的
以前我们创建一个javabean
/** * 自定义pojo */ public static class Teacher { private String name; private Integer age; @Override public String toString() { return "Teacher{" + "name='" + name + '\'' + ", age=" + age + '}'; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
然后给它赋值
Teacher teacher = new Teacher(); teacher.setName("achao"); teacher.setAge(91); System.out.println(teacher);
建造者模式的话,写起来就要像这样
/** * 自定义pojo */ public static class Student { private String name; private Integer age; public Student() { } private Student(Student student) { this.name = student.name; this.age = student.age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } private static Builder builder() { return new Builder(); } public static class Builder { private Student student; public Builder() { this.student = new Student(); } public Student build() { return new Student(this.student); } public Builder name(String name) { this.student.name = name; return this; } public Builder age(Integer age) { this.student.age = age; return this; } }
用起来就是这样
Student ruben = Student.builder().name("ruben").age(19).build(); System.out.println(ruben);
那么,每次这么写肯定受不了,于是我们可以使用lombok
只需要在我们的javabean
上加个@Builder
注解就可以使用建造者模式了
通过查看编译后的class
文件可以看到Lombok
和我们写的差不多,只不过它用的是全参构造
仿照他的写出来就是这样的
/** * 自定义pojo */ public static class Student { private String name; private Integer age; Student(String name, Integer age) { this.name = name; this.age = age; } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } private static StudentBuilder builder() { return new StudentBuilder(); } public static class StudentBuilder { private String name; private Integer age; StudentBuilder() { } public StudentBuilder name(String name) { this.name = name; return this; } public StudentBuilder age(Integer age) { this.age = age; return this; } public Student build() { return new Student(name, age); } @Override public String toString() { return "StudentBuilder{" + "name='" + name + '\'' + ", age=" + age + '}'; } } }