Builder属于创建型设计模式
Builder定义:
Separate the construction of a complex object from its representation,so that the same construction process can create different representations
将复杂对象的构造与其表示分离,以便相同的构造过程可以创建不同的表示
优点:
1.创建对象时可根据需要设置属性,自由度更大
2.链式设置属性,代码更简洁
3.具体的建造者类之间是相互独立的,这有利于系统的扩展
4.build()方法规避风险,在每个参数引用之前进行判断拦截
使用场景:
Builder模式用于创建一个比较复杂的类,参数多,且很多参数都有可以默认值
使用方式:
1.在静态内部类中创建当前类对象
2.多态+泛型 创建当前对象
方式一:在静态内部类中创建当前类对象(比如Android中的AlertDialog和OKhttpClient的创建)
private static class Builder {
private String title;
private String msg;
private OnClickListener onClickListener;
public Builder title(String title) {
this.title = title;
return this;
}
public Builder msg(String msg) {
this.msg = msg;
return this;
}
public Builder setOnClickListener(OnClickListener onClickListener) {
this.onClickListener = onClickListener;
return this;
}
public Dialog build() {
if ("".equals(title) || title == null) {
throw new NullPointerException("title 不能为空");
}
if ("".equals(msg) || msg == null) {
throw new NullPointerException("msg 不能为空");
}
Dialog dialog = new Dialog(title, msg);
if (onClickListener != null) {
dialog.setOnClickListener(onClickListener);
}
return dialog;
}
}
链式调用
new Builder()
.title("复工")
.msg("离复工还有1天")
.setOnClickListener(new OnClickListener() {
@Override
public void onClick() {
System.out.println("点击开工");
}
})
.build()
.show()
.onClick();
方式二.多态+泛型

源码链接:https://github.com/A18767101271/java-/tree/master/src/chapter_pattern/builder
网友评论