定义
指将一个复杂对象的构造和表示分离,使同样的构建过程可以创建不同的表示。建造者模式属于创建型模式。
优点
- 封装性好,构建和表示分离;
- 解耦,具体的建造者相互独立;
- 易于使用创建,不需要知道具体参数。
缺点
- 产品的组成部分必须相同,限制了其使用范围;
- 如果产品内部发生变化,建造者要跟着改变。
使用场景
创建一个属性很多的对象时,每次创建不需要知道全部的属性。
实现
建造者模式由产品类、抽象建造者、具体建造者、指挥者构成
/**
* 产品类
*/
public class Product {
private int id;
private String title;
private String content;
public void setId(int id) {
this.id = id;
}
public void setTitle(String title) {
this.title = title;
}
public void setContent(String content) {
this.content = content;
}
public void tostring() {
Log.e("test","Product{" +
"id=" + id +
", title='" + title + '\'' +
", content='" + content + '\'' +
'}');
}
}
/**
* 抽象建造者
*/
public abstract class Builder {
//创建产品对象
protected Product mProduct=new Product();
protected abstract Product create();
protected abstract void buildId(int id) ;
protected abstract void buildTitle(String title) ;
protected abstract void buildContent(String content) ;
}
/**
* 具体构造者
*/
public class ConcreteBuilder extends Builder {
@Override
protected Product create() {
return mProduct;
}
@Override
protected void buildId(int id) {
mProduct.setId(id);
}
@Override
protected void buildTitle(String title) {
mProduct.setTitle(title);
}
@Override
protected void buildContent(String content) {
mProduct.setContent(content);
}
}
/**
* 指挥者类
*/
public class Director {
private Builder mBuilder;
public Director(Builder builder){
mBuilder=builder;
}
//产品构建与组装方法
public Product construct(int id,String title,String content){
mBuilder.buildId(id);
mBuilder.buildTitle(title);
mBuilder.buildContent(content);
return mBuilder.create();
}
}
//建造者模式实现
Builder builder=new ConcreteBuilder();
Director director=new Director(builder);
director.construct(0,"nihao","你好").tostring();
简单实现
/**
* 参数类
*/
public class MyParams {
public int id;
public String content;
public int tcColor;
public int tcSize;
public String title;
public int ttColor;
public int ttSize;
}
/**
* 自定义产品类
*/
public class MyView {
private MyParams params;
public MyView(MyParams params) {
this.params = params;
}
public void getContent() {
Log.e("test", params.content);
}
/**
* 建造者 同时扮演者抽象建造者(Builder)、Director(指挥者类)
*/
public static class Builder {
private MyParams mParams;
public Builder() {
mParams = new MyParams();
}
public Builder setId(int id) {
mParams.id = id;
return this;
}
public Builder setContent(String content) {
mParams.content = content;
return this;
}
public Builder setTcColor(int tcColor) {
mParams.tcColor = tcColor;
return this;
}
public Builder setTcSize(int tcSize) {
mParams.tcSize = tcSize;
return this;
}
//此处省略属性设置...
//创建产品对象 (类似指挥者类的功能)
public MyView build() {
return new MyView(mParams);
}
}
}
//建造者模式实现
MyView view=new MyView.Builder()
.setContent("你好")
.build();
view.getContent();