喜欢用guava的原因之一就是喜欢guava的编码风格,guava的fluent风格的api使用起来非常清爽,其中内部实现就使用了Builder模式
1 在使用不可变集合ImmutableList时,可以直接初始化:
ImmutableListstrings = ImmutableList.of("1", "2");
因为ImmutableList是一个不可变集合,初始化后就不能改变;但是当你一下子无法确定集合的值时,你需要多次添加才能确定,这时我们就可以使用Builder模式,guava的ImmutableList提供了一个内部类,
ImmutableList.Builder
ImmutableList.Builderbuilder = new ImmutableList.Builder (); builder.add("hi"); builder.add("name"); ImmutableList immutableList = builder.build();
ImmutableList提供了一个内部类Builder
public static final class Builderextends ImmutableCollection.ArrayBasedBuilder { @Override public ImmutableList build() { return asImmutableList(contents, size); } } abstract static class ArrayBasedBuilder extends ImmutableCollection.Builder { Object[] contents; int size; ArrayBasedBuilder(int initialCapacity) { checkNonnegative(initialCapacity, "initialCapacity"); this.contents = new Object[initialCapacity]; this.size = 0; } }
由上面可以看出,Builder
这种代码的好处:清爽的Fluent风格的api,可以进行多次构造,代码极易阅读
2 下面可以举一个例子,用来说明Builder模式非常不错,贴合实际:
假如有一个User类,有四个属性attr1, attr2, attr3, attr4,当你想提供支持不同参数的构造函数时, 你可能要写类似如下的代码:
User (String attr1, String attr2, String attr3, String attr4) { //do something.. } User (String attr1) { //do something.. } User (String attr1, String attr2) { //do something.. } User (String attr1, String attr2, String attr3) { //do something.. }
当别人调用你的构造方法时,就会很困惑,我的参数究竟对应哪几个属性, 你可能要去看一下代码的具体实现才能搞清楚;
现在用Builder模式就很容易解决上面的困惑,我们在上面的User类中定义一个内部类Builder,代码如下:
public static class Builder { private String attr1 = ""; private String attr2 = ""; private String attr3 = ""; private String attr4 = ""; public Builder attr1 (String attr1) { this.attr1 = attr1; return this; } public Builder attr2 (String attr2) { this.attr2 = attr2; return this; } public Builder attr3 (String attr3) { this.attr3 = attr3; return this; } public Builder attr4 (String attr4) { this.attr4 = attr4; return this; } public User build () { return new User(this.attr1, this.attr2, this.attr3, this.attr4); } }
内部类Builder持有的属性和User类相同,不同时,Builder提供了Fluent风格的结构,让api调用起来更加方面,如下:
User user = new User.Builder().attr1("attr1").attr2("attr2").attr3("attr3").attr4("attr4").build();
这样再构造User对象时,你可以清楚的知道自己对哪个属性指定了属性值
3 google 代码中大量使用了Builder模式,有兴趣的可以研究一下Gson,Gson对象的创建就提供了Builder模式的创建,GsonBuilder,提供gson对象的创建,支持创建过程中大量的自定义操作:
使用Gson的时候可以直接创建一个Gson对象:
Gson gson = new Gson();当用gson时,很多操作比如日期格式化都是按照默认的方式,Gson支持很多自定义的操作,构建Gson对象的时候可以使用一个Builder,可以添加很多自定义的操作,google提供了GsonBuilder,原理与上面的代码一样:
GsonBuilder中持有大量Gson对象可以设置的属性的引用,通过GsonBuilder的方法来设置这些属性,最后调用create()方法,把这些属性放入到Gson对象中:
public final class GsonBuilder { //GsonBuilder持有大量的Gson对象可设置的属性 private Excluder excluder = Excluder.DEFAULT; private LongSerializationPolicy longSerializationPolicy = LongSerializationPolicy.DEFAULT; private FieldNamingStrategy fieldNamingPolicy = FieldNamingPolicy.IDENTITY; private final Map通过GsonBuilder我们可以自定义Gson对象的很多属性:> instanceCreators = new HashMap >(); private final List factories = new ArrayList (); /** tree-style hierarchy factories. These come after factories for backwards compatibility. */ private final List hierarchyFactories = new ArrayList (); private boolean serializeNulls; private String datePattern; private int dateStyle = DateFormat.DEFAULT; private int timeStyle = DateFormat.DEFAULT; private boolean complexMapKeySerialization; private boolean serializeSpecialFloatingPointValues; private boolean escapeHtmlChars = true; private boolean prettyPrinting; private boolean generateNonExecutableJson; //通过GsonBuilder提供的方法可以设置这些属性... //把GsonBuilder持有的属性值设置到Gson对象中 public Gson create() { List factories = new ArrayList (); factories.addAll(this.factories); Collections.reverse(factories); factories.addAll(this.hierarchyFactories); addTypeAdaptersForDate(datePattern, dateStyle, timeStyle, factories); return new Gson(excluder, fieldNamingPolicy, instanceCreators, serializeNulls, complexMapKeySerialization, generateNonExecutableJson, escapeHtmlChars, prettyPrinting, serializeSpecialFloatingPointValues, longSerializationPolicy, factories); }