更简洁的Builder模式?

时间:2015-02-04 21:47:34

标签: java builder

当我在Josh的Bloch书中查看 Builder模式时,我想出了更简单的实现,但我不确定它是否合适。 例如:

public class Test {
    public static void main(String[] args) {
        Numbers first = new Numbers.Builder().setD(3.14).build();
        System.out.println(first);
        Numbers second = new Numbers.Builder().setI(17).setF(1.24F).build();
        System.out.println(second);
        System.out.println(first);
    }
}

final class Numbers {
    private int i;
    private long l;
    private float f;
    private double d;

    private Numbers() {}


    public static class Builder {
        private final Numbers instance = new Numbers();

        public Builder setI(int i) {
            instance.i = i;
            return this;
        }

        public Builder setL(long l) {
            instance.l = l;
            return this;
        }

        public Builder setF(float f) {
            instance.f = f;
            return this;
        }

        public Builder setD(double d) {
            instance.d = d;
            return this;
        }

        public Numbers build() {
            return instance;
        }
    }

    @Override
    public String toString() {
        return String.format("%4d %4d %7.3f %7.3f", i, l, f, d);
    }
}

它是否仍然可以被视为 Builder模式或者我错过了什么?

修改

这个怎么样?

//...

private Numbers() {}


private Numbers(Numbers o) {
        i = o.i;
        l = o.l;
        f = o.f;
        d = o.d;
    }

public static class Builder {
        private final Numbers instance = new Numbers();

          //...

        public Numbers build() {
            return new Numbers(instance);
        }
    }

1 个答案:

答案 0 :(得分:4)

您的代码存在的问题是,如果您为同一个build实例调用Builder两次,则会获得相同的Numbers实例。如果在调用Builder并获得build实例后调用Numbers的方法,则会更改该实例。构建器创建的实例在构建后应独立于Builder。