Builder模式的目的:
将一个复杂对象的构建和它的表示分离,使得同样的构建过程可以创建不同的表示。
Builder模式的好处:
用户可以通过该模式一步一步创建一个复杂对象,使得用户可以在不知道内部构建细节的情况下,可以更精细的控制对象的构件流程。
目前Builder模式多分为简略版与经典版
简略版:
public class Person {
private final String name; //属性都被final修饰,不可变
private final int age;
private final String phone;
private Person(PersionBuilder builder) { //该bean类构造函数私有,使用者不可以直接调用来创建对象
this.name = builder.name;
this.age = builder.age;
this.phone = builder.phone;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getPhone() {
return phone;
}
public static class PersionBuilder {
private final String name;
private int age;
private String phone;
public PersionBuilder(String name) { //Builder类的构造函数中限定了必须传的属性
this.name = name;
}
public PersionBuilder age(int age) {
this.age = age;
return this;
}
public PersionBuilder phone(String phone) {
this.phone = phone;
return this;
}
public Person build() {
return new Person(this);
}
}
}
调用代码如下:
Person person = new Person.PersionBuilder("小明")
.age(12)
.phone("13111111111")
.build();
经典版:
Builder模式角色介绍:
Product 抽象的产品类
ConcreteProduct 具体的产品类,实现抽象类
Builder 抽象的生产者类,规范生产者功能
ConcreteBuilder 具体的生产者类,实现生产者的各个功能
Director 指挥类,负责指挥建造者进行建造组装
抽象的产品类:
public abstract class Product {
private String mName;
private String mColor;
public void setName(String name){
this.mName = name;
}
public void setColor(String color){
this.mColor = color;
}
public String getName(){
return mName;
}
public String getColor() {
return mColor;
}
public abstract String showInfoProduct();
}
具体的产品类:
这里假设该具体产品多了一个Size的需求,得益于多态,可于这里直接进行功能的扩展
public class ConcreteProduct extends Product {
private int mSize;
@Override
public String showInfoProduct() {
return "Name:" + getName() + " Color:" + getColor() + " " + " Size:" + getSize();
}
public void setSize(int size) {
this.mSize = size;
}
public int getSize() {
return mSize;
}
}
抽象的生产者类
public abstract class Builder {
public abstract void buildName(String name);
public abstract void buildColor(String color);
public abstract Product create();
}
具体的生产者类:
于该产品create时,直接指定了该产品的大小
public class ConcreteBuilder extends Builder {
private ConcreteProduct mProduct = new ConcreteProduct();
@Override
public void buildName(String name) {
mProduct.setName(name);
}
@Override
public void buildColor(String color) {
mProduct.setColor(color);
}
@Override
public Product create() {
mProduct.setSize(10);
return mProduct;
}
}
指挥类:
该类保证了不对外暴露任何生产细节,只需传入参数,返回对应产品
public class Director {
Builder mBuild=null;
public Director(Builder build){
this.mBuild=build;
}
public Product CreateProduct(String name, String color){
//规范建造流程
this.mBuild.buildName(name);
this.mBuild.buildColor(color);
return mBuild.create();
}
}
调用方法:
Builder mBuilder=new ConcreteBuilder();
Director mDirecror=new Director(mBuilder);
//组装产品
Product product = mDirecror.CreateProduct("X1","Red");
Log.i("Builder","产品信息:"+product.showInfoProduct());