jeudi 29 septembre 2016

Keeping builder in seperate class (fluent interface)

Foo foo = Foo.builder()
    .setColor(red)
    .setName("Fred")
    .setSize(42)
    .build();

So I know there is the following "Builder" solution for creating named parameters when calling a method. Although, this only seems to work with inner static classes as the builder or am I wrong? I had a look at some tutorials for builder pattern but they seem really complex for what im trying to do. Is there any way to keep the Foo class and Builder class seperate while having the benefit of named parameters like the code above?

Below a typical setup:

   public class Foo {
      public static class Builder {
        public Foo build() {
          return new Foo(this);
        }

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

        public Builder setColor(Color color) {
          this.color = color;
          return this;
        }

        public Builder setName(String name) {
          this.name = name;
          return this;
        }

        // you can set defaults for these here
        private int size;
        private Color color;
        private String name;
      }

      public static Builder builder() {
          return new Builder();
      }

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

      private final int size;
      private final Color color;
      private final String name;
    }

Aucun commentaire:

Enregistrer un commentaire