名词解释
Builder Pattern
将一个复杂对象的构建过程与它的表示分离,使得同样的构建过程可以创建不同的表示,属于创建型模式。
使用建造者模式对于用户而言只需要指定需要建造的
类型
和内容
就可以获得对象,建造过程及细节不需要了解,其根本目的是解耦过程
和部件
。
适用场景
适用于创建对象需要很多步骤,且步骤的顺序不一定固定。为了达到灵活创建对象的目的,可以使用建造者模式。另外,如果采用链式编程的写法,也可以是代码更简洁一些。
写法
- 创建一个静态内部类 Builder,然后将所用参数从外部类copy到 Builder中,内部类的取名最好和外部类保持一致,如外部类叫Computer,内部类则叫ComputerBuilder;
- 内部类提供一个包含所有必填参数的公共构造函数;
- 内部类提供可以设置可选参数的方法,改方法返回Builder对象本身(链式编程);
- 最后,内部类提供一个build()方法,用于生成最终的外部类对象,所以,外部类,应该
提供一个私有的参数为内部类的构造函数
/**
* 必填参数
*/
private String HDD;
private String RAM;
/**
* 可选参数
*/
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
public String getHDD() {
return HDD;
}
public String getRAM() {
return RAM;
}
public boolean isGraphicsCardEnabled() {
return isGraphicsCardEnabled;
}
public boolean isBluetoothEnabled() {
return isBluetoothEnabled;
}
private Computer(ComputerBuilder builder) {
this.HDD = builder.HDD;
this.RAM = builder.RAM;
this.isGraphicsCardEnabled = builder.isGraphicsCardEnabled;
this.isBluetoothEnabled = builder.isBluetoothEnabled;
}
@Override
public String toString() {
return "Computer{" +
"HDD='" + HDD + '\'' +
", RAM='" + RAM + '\'' +
", isGraphicsCardEnabled=" + isGraphicsCardEnabled +
", isBluetoothEnabled=" + isBluetoothEnabled +
'}';
}
/**
* 建造者类
*/
public static class ComputerBuilder{
/**
* 必填参数
*/
private String HDD;
private String RAM;
/**
* 可选参数
*/
private boolean isGraphicsCardEnabled;
private boolean isBluetoothEnabled;
public ComputerBuilder(String hdd, String ram){
this.HDD=hdd;
this.RAM=ram;
}
public ComputerBuilder setGraphicsCardEnabled(boolean isGraphicsCardEnabled) {
this.isGraphicsCardEnabled = isGraphicsCardEnabled;
return this;
}
public ComputerBuilder setBluetoothEnabled(boolean isBluetoothEnabled) {
this.isBluetoothEnabled = isBluetoothEnabled;
return this;
}
public Computer build(){
return new Computer(this);
}
}
测试类
public static void main(String[] args) {
//Using builder to get the object in a single line of code and
//without any inconsistent state or arguments management issues
Computer comp = new Computer.ComputerBuilder("500 GB", "2 GB")
.setBluetoothEnabled(true)
.setGraphicsCardEnabled(true).build();
System.out.println(comp);
}
源码中应用
- JDK的 java.lang.StringBuilder#append() (unsynchronized)
- JDK的 java.lang.StringBuffer#append() (synchronized)
- MyBatis 的CacheBuilder和SqlSessionFactoryBuilder
- Spring中的 BeanDefinitionBuilder