建造者模式定义
建造者模式是较为复杂的创建型模式,它将客户端与包含多个组成部分(或部件)的复杂对象的创建过程分离,客户端无须知道复杂对象的内部组成部分与装配方式,只需要知道所需建造者的类型即可。它关注如何一步一步创建一个的复杂对象,不同的具体建造者定义了不同的创建过程,且具体建造者相互独立,增加新的建造者非常方便,无须修改已有代码,系统具有较好的扩展性。
建造者模式定义如下:
建造者模式(Builder Pattern):将一个复杂对象的构建与它的表示分离,使得同样的构建过程可以创建不同的表示。建造者模式是一种对象创建型模式。
建造者模式一步一步创建一个复杂的对象,它允许用户只通过指定复杂对象的类型和内容就可以构建它们,用户不需要知道内部的具体构建细节。
建造者模式的结构关系图如下:
在建造者模式结构图中包含如下几个角色:
- Builder(抽象建造者):它为创建一个产品Product对象的各个部件指定抽象接口,在该接口中一般声明两类方法,一类方法是buildPartX(),它们用于创建复杂对象的各个部件;另一类方法是getResult(),它们用于返回复杂对象。Builder既可以是抽象类,也可以是接口。
- ConcreteBuilder(具体建造者):它实现了Builder接口,实现各个部件的具体构造和装配方法,定义并明确它所创建的复杂对象,也可以提供一个方法返回创建好的复杂产品对象。
- Product(产品角色):它是被构建的复杂对象,包含多个组成部件,具体建造者创建该产品的内部表示并定义它的装配过程。
- Director(指挥者):指挥者又称为导演类,它负责安排复杂对象的建造次序,指挥者与抽象建造者之间存在关联关系,可以在其construct()建造方法中调用建造者对象的部件构造与装配方法,完成复杂对象的建造。客户端一般只需要与指挥者进行交互,在客户端确定具体建造者的类型,并实例化具体建造者对象(也可以通过配置文件和反射机制),然后通过指挥者类的构造函数或者Setter方法将该对象传入指挥者类中。
建造者模式的示例代码
产品:
class Product {
private String productName;
private String location;
private String country;
private Date birth;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
}
构造者:
interface Builder {
void productName(String productName);
void location(String location);
void country(String country);
void birth(Date birth);
Product build();
}
class ProductBuilder implements Builder {
private String productName;
private String location;
private String country;
private Date birth;
public void productName(String productName) {
this.productName = productName;
}
public void location(String location) {
this.location = location;
}
public void country(String country) {
this.country = country;
}
public void birth(Date birth) {
this.birth = birth;
}
public Product build() {
Product product = new Product();
product.setProductName(this.productName);
product.setLocation(this.location);
product.setCountry(this.country);
product.setBirth(this.birth);
return product;
}
}
指挥者:
class Director {
private Builder builder;
public Director(Builder builder) {
this.builder = builder;
}
public Product makeProduct(String productName, String location, String country, Date birth) {
builder.productName(productName);
builder.location(location);
builder.country(country);
builder.birth(birth);
return builder.build();
}
}
客户端调用如下:
public static void main(String[] args) {
Builder builder = new ProductBuilder();
Director director = new Director(builder);
Product product = director.makeProduct("产品", "Beijing", "China", new Date());
}
建造者省略指挥者
为了简化系统结构,有时会将指挥者省略,并且会将创建者声明到产品类中,修改后的代码如下:
class Product {
private String productName;
private String location;
private String country;
private Date birth;
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Date getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
static class Builder{
private String productName;
private String location;
private String country;
private Date birth;
public Builder productName(String productName) {
this.productName = productName;
return this;
}
public Builder location(String location) {
this.location = location;
return this;
}
public Builder country(String country) {
this.country = country;
return this;
}
public Builder birth(Date birth) {
this.birth = birth;
return this;
}
public Product build() {
Product product = new Product();
product.setProductName(this.productName);
product.setLocation(this.location);
product.setCountry(this.country);
product.setBirth(this.birth);
return product;
}
}
}
那么在客户端调用如下:
public static void main(String[] args) {
Product product = new Product.Builder().productName("banana")
.location("Haikou")
.country("China")
.birth(new Date())
.build();
}
建造者模式的优缺点
优点:
- 在建造者模式中,客户端不必知道产品内部组成的细节,将产品本身与产品的创建过程解耦,使得相同的创建过程可以创建不同的产品对象。
- 每一个具体建造者都相对独立,而与其他的具体建造者无关,因此可以很方便地替换具体建造者或增加新的具体建造者,用户使用不同的具体建造者即可得到不同的产品对象。由于指挥者类针对抽象建造者编程,增加新的具体建造者无须修改原有类库的代码,系统扩展方便,符合“开闭原则”
- 可以更加精细地控制产品的创建过程。将复杂产品的创建步骤分解在不同的方法中,使得创建过程更加清晰,也更方便使用程序来控制创建过程。
缺点:
- 建造者模式所创建的产品一般具有较多的共同点,其组成部分相似,如果产品之间的差异性很大,例如很多组成部分都不相同,不适合使用建造者模式,因此其使用范围受到一定的限制。
- 如果产品的内部变化复杂,可能会导致需要定义很多具体建造者类来实现这种变化,导致系统变得很庞大,增加系统的理解难度和运行成本。
源码中建造者模式的使用
接下来看一下源码中建造者模式的使用。
JDK中建造者模式的使用
在JDK中StringBuilder就是使用的构建者模式,StringBuilder是一个可变对象,使用一个char数组用于容纳数据:
char[] value;
int count;
这有点像ArrayList的实现一样,count用于记录实际的字符长度。其多个重载的append方法。就是用于动态的指定字符串中的内容,当调用其toString方法后则会返回一个String对象:
@Override
public String toString() {
// Create a copy, don't share the array
return new String(value, 0, count);
}
Calendar的构建也是使用了构造者模式,JDK中的Calendar是工厂模式和构造模式结合使用,工厂模式用于处理不同的时区和本地化的问题,而构造者模式则用于构建日期中的年月日等信息。
而其build方法如下:
public Calendar build() {
if (locale == null) {
locale = Locale.getDefault();
}
if (zone == null) {
zone = TimeZone.getDefault();
}
Calendar cal;
if (type == null) {
type = locale.getUnicodeLocaleType("ca");
}
if (type == null) {
if (locale.getCountry() == "TH"
&& locale.getLanguage() == "th") {
type = "buddhist";
} else {
type = "gregory";
}
}
switch (type) {
case "gregory":
cal = new GregorianCalendar(zone, locale, true);
break;
case "iso8601":
GregorianCalendar gcal = new GregorianCalendar(zone, locale, true);
// make gcal a proleptic Gregorian
gcal.setGregorianChange(new Date(Long.MIN_VALUE));
// and week definition to be compatible with ISO 8601
setWeekDefinition(MONDAY, 4);
cal = gcal;
break;
case "buddhist":
cal = new BuddhistCalendar(zone, locale);
cal.clear();
break;
case "japanese":
cal = new JapaneseImperialCalendar(zone, locale, true);
break;
default:
throw new IllegalArgumentException("unknown calendar type: " + type);
}
cal.setLenient(lenient);
if (firstDayOfWeek != 0) {
cal.setFirstDayOfWeek(firstDayOfWeek);
cal.setMinimalDaysInFirstWeek(minimalDaysInFirstWeek);
}
if (isInstantSet()) {
cal.setTimeInMillis(instant);
cal.complete();
return cal;
}
if (fields != null) {
boolean weekDate = isSet(WEEK_YEAR)
&& fields[WEEK_YEAR] > fields[YEAR];
if (weekDate && !cal.isWeekDateSupported()) {
throw new IllegalArgumentException("week date is unsupported by " + type);
}
// Set the fields from the min stamp to the max stamp so that
// the fields resolution works in the Calendar.
for (int stamp = MINIMUM_USER_STAMP; stamp < nextStamp; stamp++) {
for (int index = 0; index <= maxFieldIndex; index++) {
if (fields[index] == stamp) {
cal.set(index, fields[NFIELDS + index]);
break;
}
}
}
if (weekDate) {
int weekOfYear = isSet(WEEK_OF_YEAR) ? fields[NFIELDS + WEEK_OF_YEAR] : 1;
int dayOfWeek = isSet(DAY_OF_WEEK)
? fields[NFIELDS + DAY_OF_WEEK] : cal.getFirstDayOfWeek();
cal.setWeekDate(fields[NFIELDS + WEEK_YEAR], weekOfYear, dayOfWeek);
}
cal.complete();
}
return cal;
}