标签:
建造者模式
建造者模式实现
示例代码
使用
jdk中的应用
和工厂、抽象工厂设计模式一样,builder设计模式也是对象创建类型中的一种。当创建的对象比较复杂的时候,特别是包含的属性比较多,工厂方法创建此类对象是比较麻烦的,builder是为了解决这类问题而引入的。 工厂方法创建此类对象时主要有以下几类问题需要解决:
当有很多参数的时候,特别是当这些参数比较多的时候,client在调用工厂类创建对象的时候很容易出错。
其中传递的参数,有些是必须要传递的,而有些是可选的,此时,我们需要设置可选的参数为null。
如果对象很重,创建的过程比较复杂,这会使得工厂类更复杂。
我们可以提供一个只包含必须传递参数的构造函数,另外在提供可选字段的set方法来设置可选的参数。但是这种方法,要显示的调用的set方法来保证对象状态的一致性。
建造者设计模式可以使得我们一步一步创建对象,并能返回最终的对象,进而避免上述问题。
首先创建一个静态内部类,把外部类的所有属性拷贝到静态内部类里面,同时为了遵循命名的规范,我们以类名Builder来命名内部类。
静态内部类包含一个public的构造函数,所有必需传递的参数作为构造函数的参数。
静态内部类应该提供设置可选参数的入口,即可选参数对应的set方法同时当连续调用多个属性的set方法之后,应该保证返回的是同一个builder对象。
最后一步要在静态内部类中实现一个builder方法,这个方法会返回外部类的对象。通过在外部类中实现一个private的私有构造函数,静态内部类作为参数来实现。
public class Computer {
//required parameters
private String HDD;
private String RAM;
//optional parameters
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 + "]";
}
//Builder Class
public static class ComputerBuilder {
// required parameters
private String HDD;
private String RAM;
// optional parameters
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 class TestBuilderPattern {
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
Computer comp = new Computer.ComputerBuilder(
"500 GB", "2 GB").setBluetoothEnabled(true)
.setGraphicsCardEnabled(true).build();
System.out.println(comp);
//Computer [HDD=500 GB, RAM=2 GB, isGraphicsCardEnabled=true, isBluetoothEnabled=true]
}
}
java.lang.StringBuilder#append() (unsynchronized)
java.lang.StringBuffer#append() (synchronized)
标签:
原文地址:http://my.oschina.net/lianlupeng/blog/489828