使用许多私有集合字段构造对象

时间:2013-08-15 10:38:07

标签: java constructor coding-style

创建类的对象的最强高效干净方式是什么,该类具有10个私有字段作为集合(例如,HashMap,LinkedHashMap,ArrayList等) )。

如果我在其中放置一个包含10个字段的构造函数,它看起来就像是噩梦。

3 个答案:

答案 0 :(得分:2)

Builder pattern

怎么样?
YourClass obj = YourClass.setCollection1(...)
                           .setCollection2(...)
                             .setCollection3(...)......
                                                  .build();

额外的好处是您只需传递所需的值,其余的将保留其默认值。

答案 1 :(得分:2)

您可以像这样使用Builder

public class Pojo {

    private String field1;
    private String field2;
    private String field3;
    private String field4;
    private String field5;

    public Pojo(PojoBuilder pojoBuilder) {
        this.field1 = pojoBuilder.field1;
        this.field2 = pojoBuilder.field2;
        this.field3 = pojoBuilder.field3;
        this.field4 = pojoBuilder.field4;
        this.field5 = pojoBuilder.field5;
    }

    public static class PojoBuilder {
        String field1;
        String field2;
        String field3;
        String field4;
        String field5;

        public PojoBuilder field1(String field1) {
            this.field1 = field1;
            return this;
        }

        public PojoBuilder field2(String field2) {
            this.field2 = field2;
            return this;
        }
        public PojoBuilder field3(String field3) {
            this.field3 = field3;
            return this;
        }
        public PojoBuilder field4(String field4) {
            this.field4 = field4;
            return this;
        }
        public PojoBuilder field5(String field5) {
            this.field5 = field5;
            return this;
        }

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

    }

    public String getField1() {
        return field1;
    }

    public String getField2() {
        return field2;
    }

    public String getField3() {
        return field3;
    }

    public String getField4() {
        return field4;
    }

    public String getField5() {
        return field5;
    }


}

你可以像这样使用它:

Pojo pojo = new PojoBuilder().field1("field1").field1("field2").field1("field3").field1("field4").field1("field5").build();

我经常使用这种模式来构建不可变的pojos。

答案 2 :(得分:0)

考虑Builder Pattern

YourClass classObject = new YourClass.name("someName").age(26).Sex("M").build();