Is the nested Builder class really necessary, as described in Efficient Java?

So, in the famous Effective Java book, the Builder template is introduced , where you can have an internal static class Builder to create an instance of the class. The following class design is proposed in the book:

public class Example {
    private int a;
    private int b;

    public static class Builder() {
        private int a;
        private int b;

        public Builder a(int a) {
            this.a = a;
            return this;
        }

        public Builder b(int b) {
            this.b = b;
            return this;
        }

        public Example build() {
            return new Example(this);    
        }
    }

    private Example(Builder builder) {
        this.a = builder.a;
        this.b = builder.b;
    }
}

However, I could not understand why we really need an internal one Builder class? . The above code has duplicate lines for field declarations (int a, b), this will become relatively messy if we had more fields.

Why not just get rid of the class Builder, and Exampletake the class all the methods setthat were in the class Builder?

, Example, Example e = new Example().a(3).b.(3); Example e = new Example.Builder.a(3).b(3).build();


. , .

+4
3

Builder - . ; , , .

, :

  • . ( ) , .

    , N , . 2 ^ N , , "", . : , setter.

  • . , , .

    , , , .

+9

, , , .

builder .

, . ; , .

, . StringBuilder. . "build" toString().

, , . -, , , , super(), , , super(...). BoxLayout . JPanel BoxLayout. JPanel. . , this .

class X extends JPanel {
    X() {
        super( new BoxLayout(this) );   // Error: Cannot use "this" yet
    }
}

, JPanel ; .

+1

- . , Builder , , :

Example exp = Example.Builder().a(5).b(10).build();

Apache uses this approach in some cases to provide incremental customization of various values. It also allows the method .build()to do some validation of all the correct values ​​to create the object, if necessary.

+1
source

All Articles