Builder(建造者模式)
建造者模式:是将一个复杂的对象的构建与它的表示分离(同构建不同表示),使得同样的构建过程可以创建不同的表示。
将复杂的内部创建封装在内部,对于外部调用的人来说,只需要传入建造者和建造工具,对于内部是如何建造成成品的,调用者无需关心。
使用场景:
1、相同的方法,不同的执行顺序,产生不同的事件结果
2、对象比较复杂,参数比较多。
示例代码:
public class School {
private final String teacher;
private final String student;
private final String flower;
private final String grass;
private final String library;
public static class Builder {
//必选参数
private String teacher;
private String student;
//可选参数
private String flower;
private String grass;
private String library;
//通过builder模式,给对象添加属性;
public Builder(String teacher, String student) {
this.teacher = teacher;
this.student = student;
}
public Builder flower(String flower) {
this.flower = flower;
return this;
}
public Builder grass(String grass) {
this.grass = grass;
return this;
}
public Builder library(String library) {
this.library = library;
return this;
}
//返回外部对象
public School build() {
return new School(this);
}
}
private School(Builder builder) {
this.teacher = builder.teacher;
this.student = builder.student;
this.flower = builder.flower;
this.grass = builder.grass;
this.library = builder.library;
}
}
/**
* 测试类
*/
public static void main(String[] args) {
School school = new School.Builder("王老师", "好学生")
.flower("玫瑰花")
.grass("海草")
.library("音乐书")
.build();
}
Android
中Builder
模式也是常见的,最熟悉的是Dialog
使用传统的重叠构造器模式相比,使用builder
模式的客户端代码装将更易于阅读和编写,构建器也比JavaBeans
更加安全。
网友评论