Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Less verbose Builder pattern?

Tags:

java

builder

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);
        }
    }
like image 487
Dmytro Avatar asked Sep 29 '22 20:09

Dmytro


1 Answers

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.

like image 134
Eran Avatar answered Oct 07 '22 21:10

Eran