Dmytro
Dmytro

Reputation: 2009

Less verbose Builder pattern?

When i was reviewing Builder pattern in Josh's Bloch book, i came up with simpler implementation, but i'm not sure whether it's proper. For example:

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);
    }
}

Is it can still be considered as a Builder pattern or i missed something?

EDIT

What about this?

//...

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);
        }
    }

Upvotes: 5

Views: 467

Answers (1)

Eran
Eran

Reputation: 393936

The problem with your code is that if you call build twice for the same Builder instance, you'll get the same Numbers instance. And if you call methods of the Builder after you called build and got the Numbers instance, you will change that instance. The instance created by the builder should be independent of the Builder once it's built.

Upvotes: 4

Related Questions