建造者模式实现了Cloneable接口并重写了clone()方法,但是与其复制建造者的每个字段不同,不可变类会保留一个私有的建造者克隆。这样可以轻松地返回一个新的建造者,并创建不可变实例的稍微修改副本。
这样我就可以继续前进了。
MyImmutable i1 = new MyImmutable.Builder().foo(1).bar(2).build();
MyImmutable i2 = i1.builder().foo(3).build();
Cloneable接口被认为是有些问题的,但是这是否违反了良好的Java编程实践,这个构造中存在任何问题吗?
final class MyImmutable {
public int foo() { return builder.foo; }
public int bar() { return builder.bar; }
public Builder builder() { return builder.clone(); }
public static final class Builder implements Cloneable {
public Builder foo(int val) { foo = val; return this; }
public Builder bar(int val) { bar = val; return this; }
public MyImmutable build() { return new MyImmutable(this.clone()); }
private int foo = 0;
private int bar = 0;
@Override public Builder clone() { try { return (Builder)super.clone(); } catch(CloneNotSupportedException e) { throw new AssertionError(); } }
}
private MyImmutable(Builder builder) { this.builder = builder; }
private final Builder builder;
}