首先来看一段Android开发中经常用到的一段代码:
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("头部")
.setMessage("会话框内容")
.create();
alertDialog.show();
什么是Builder模式?为什么这么简洁的代码就能创建一个对话框?
Builder模式的定义:将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。
Builder经典模式
Builder经典模式由四个参与者构成:Product、Builder、ConcreteBuilder、Director
上代码
Product.java 被构造的复杂对象
//
public class Product {
String partA;
String partB;
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;
}
}
Builder.java 抽象接口,定义创建Product对象各个组成部件的操作
public interface Builder {
void buildPartA();
void buildPartB();
Product getProduct();
}
ConcreteBuilder.java Builder接口实现类,可定义多个。实际构建Product的地方,返回Product
public class ConcreteBuilderA implements Builder {
private Product product;
public ConcreteBuilderA() {
product = new Product();
}
@Override
public void buildPartA() {
product.setPartA("buildPartA");
}
@Override
public void buildPartB() {
}
@Override
public Product getProduct() {
return product;
}
}
public class ConcreteBuilderB implements Builder {
private Product product;
public ConcreteBuilderB() {
product = new Product();
}
@Override
public void buildPartA() {
product.setPartA("buildPartB");
}
@Override
public void buildPartB() {
}
@Override
public Product getProduct() {
return product;
}
}
Director.java : Builder接口的构造者和使用者
public class Director {
private final Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public void buildProduct() {
builder.buildPartA();
builder.buildPartB();
}
public Product getProduct() {
return builder.getProduct();
}
}
调用代码:
Director director = new Director(new ConcreteBuilderA());
director.buildProduct();
Director director = new Director(new ConcreteBuilderB());
director.buildProduct();
上面的是Builder构建的经典模式,下面介绍Builder的变种,在Android中有广泛应用。
public class User {
// 注意final
final private String firstName;
final private String lastName;
final private int age;
final private int phone;
/**
* 传入UserBuilder
* @param userBuilder
*/
private User(UserBuilder userBuilder) {
this.firstName = userBuilder.firstName;
this.lastName = userBuilder.lastName;
this.age = userBuilder.age;
this.phone = userBuilder.phone;
}
public static class UserBuilder {
// 注意final修饰的变量在构造函数赋值
final private String firstName;
final private String lastName;
private int age;
private int phone;
public UserBuilder(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public UserBuilder age(int age) {
this.age = age;
return this;
}
public UserBuilder phone(int phone) {
this.phone = phone;
return this;
}
/**
* 创建私有User
* @return 返回User
*/
public User build() {
return new User(this);
}
}
}
调用方式:
new User.UserBuilder("first", "last").age(10).phone(10086).build();
代码解析:
User类的构造方法为私有类,真正实现对User类组成部分的构建是在UserBuilder中,并在UserBuilder的build方法返回User类对象。