Repeat in builder pattern

I use the builder pattern (as explained in Joshua Bloch Effective Java) for several things, and it was particularly annoying to repeat:

public class Foo {
    private String name;
    private int age;

    public static class Builder implements IBuilder {
        private String name;
        private int age;

        Builder name(String value) {
            name = value;
            return this;
        }

        Builder age(int value) {
            age = value;
            return this;
        }

        Foo build() {
           return new Foo(this);
        }
    }

    private Foo(Builder builder) {
        name = builder.name;
        age = builder.age;
    }
}

It is small but annoying. I have to declare a variable in each class. I tried to create a class with the fields and extend this class, but I got an error: {variable_name} has private access in {class_name}.

Is there a way to do this without making the variables publicly available?

+3
source share
1 answer

If your collectors are solely for capturing a heap of state (and do not perform intermediate calculations), you can solve the repetition by simply defining the builder interface and then writing the Java proxy generator.

, , (). , . , :

public class Foo {
  public interface Builder extends IBuilder {
    Builder name(String name);
    String name();

    Builder age(int age);
    int age();
    ...
  }

  public static Builder builder() {
    return BuilderFramework.newInstance(Builder.class);
  }

  public Foo(Builder builder) {
    ...
  }
}

, Map . , . . , .

0

All Articles