定义:将一个复杂对象的构建与它的表示分离,使得同样地构建过程可以创建不同的表示
使用场景示例
我们有一个产品,它包含了很多属性
public class Product{
private String name;
private String num;
private String price;
private String weight;
}
在构造的时候通常我们使用构造函数进行初始化,但是面对许多需要初始化的属性并且有时并不需要初始化所有的属性.�构造函数就要重载,并且带着长长的参数,而建造模式就是把构建分离出来
下面是代码
public class Product {
private String name;
private String num;
private String price;
private String weight;
public Product(Builder builder) {
this.name = builder.name;
this.num = builder.num;
this.price = builder.price;
this.weight = builder.weight;
}
public static class Builder {
private String name;
private String num;
private String price;
private String weight;
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder setNum(String num) {
this.num = num;
return this;
}
public Builder setPrice(String price) {
this.price = price;
return this;
}
public Builder setWeight(String weight) {
this.weight = weight;
return this;
}
public Product create() {
return new Product(this);
}
}
}
Product.Builder builder = new Product.Builder();
Product product = builder.setName("macbook").setNum("10").create();
这种模式随处可见,典型的AlertDialog
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
View view = inflater.inflate(R.xxx, null);
builder.setView(view).setNegativeButton(DISMISS, null);
return builder.create();
}
还有URI
Uri uri = new Uri.Builder()
.scheme("xxx")
.path(String.valueOf(R.drawable.xxx))
.build();
网友评论