一,java中的 Builder模式
-
概念
构建者模式将客户端与包含多个组成部分(或部件)的复杂对象的创建过程分离 -
使用场景
当构造一个对象需要很多参数的时候,并且参数的个数和类型不固定的时候 -
UML结构图分析
image.png
总结:
1.Builder:为创建产品Product对象的各个部件指定抽象接口
2.ConcreateBuilder:实现Builder接口,实现各部件结构的构造和装配方法
3.Product:它是被构建的复杂对象,包含多个组成部件
4.Directior:指挥者,负责安排负责对象的建造次序,指挥者与抽象Builder之间存在关联关系 -
实际代码分析
public class Product {
private String partA;
private String partB;
private String partC;
public String getPartA() {
return partA;
}
public void setPartA(String partA) {
this.partA = partA;
}
public String getPartB() {
return partB;
}
public void setPartB(String partB) {
this.partB = partB;
}
public String getPartC() {
return partC;
}
public void setPartC(String partC) {
this.partC = partC;
}
}
public abstract class Builder {
protected Product product = new Product();
public abstract void buildPartA();
public abstract void buildPartB();
public abstract void buildPartC();
public Product getResult() {
return product;
}
}
public class ConcreateBuilder extends Builder{
@Override
public void buildPartA() {
}
@Override
public void buildPartB() {
}
@Override
public void buildPartC() {
}
}
public class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public void setBuilder(Builder builder) {
this.builder = builder;
}
public Product construct() {
builder.buildPartA();
builder.buildPartB();
builder.buildPartC();
return builder.getResult();
}
}
Builder builder = new ConcreateBuilder();
Director director = new Director(builder);
Product product = director.construct();
-
优点
松散耦合
容易修改内部属性
更好的复用性(具体实现以及算法都可以复用) -
缺点
产生多余的Builder对象以及Dirctor对象,消耗内存
对于构造过程的暴露
二,Builder模式在android中的应用
android中的简单实现
public class AndroidProduct {
private String partA;
private String partB;
private String partC;
private AndroidProduct(String partA, String partB, String partC) {
this.partA = partA;
this.partB = partB;
this.partC = partC;
}
public static class Builder {
private String partA;
private String partB;
private String partC;
public Builder setPartA(String partA) {
this.partA = partA;
return this;
}
public Builder setPartB(String partB) {
this.partB = partB;
return this;
}
public Builder setPartC(String partC) {
this.partC = partC;
return this;
}
public AndroidProduct build() {
return new AndroidProduct(partA, partB, partC);
}
}
}
AndroidProduct androidProduct = new AndroidProduct.Builder()
.setPartA("a")
.setPartB("b")
.setPartC("c").build();
Android中的实际应用:
1.AlertDialog
2.Gilde/okhttp
网友评论