mercredi 1 novembre 2017

What is the wrong/right way to implement the Builder pattern?

My understanding is that the builder pattern exists to avoid multiple overloaded constructors (for classes more complex than my example)

public class Example {

    private String a,b,c;

    public Example() {
       //setup defaults
    }

    public Example(String a) {
       this.a=a;
       //setup defaults
    }

    public Example(String a, String b) {
       this.a=a;
       this.b=b;
       //setup defaults
    }

    public Example(String a, String b, String c) {
       this.a=a;
       this.b=b;
       this.c=c;
    }

}

But when switching to a builder, which of the following is the correct approach to take?

public class Example {

    public static class Builder {

        //accessors

        public Example build() {
            //we setup defaults through getters
            //and example only has the 'full' constructor
            return new Example(getA(), getB(), getC()); 
        }

    }

}

OR

public class Example {

    public static class Builder {

        //accessors

        public Example build() {
            //pass in the builder and let 'Example' care about defaults
            return new Example(this); 
        }

    }

}

OR

public class Example {

    public static class Builder {

        //accessors

        public Example build() {
            //only empty constructor exists which sets all defaults
            //access fields directly to override defaults
            Example e = new Example(); 
            e.a = a;
            e.b = b;
            e.c = c;
            return e;
        }

    }

}

Are any of these breaking the builder pattern? Is there a canonically correct approach?

I know this similar question was asked but as far as I can tell (despite the name) that question only covers an actual Builder pattern vs a non-builder pattern.

I prefer the 3rd approach but many of the examples I find are using the approach of passing the builder into the constructor. I don't know if I am missing some advantage / potential problems

Aucun commentaire:

Enregistrer un commentaire