gpt4 book ai didi

java - 构造具有许多私有(private)集合字段的对象

转载 作者:行者123 更新时间:2023-12-01 18:44:48 25 4
gpt4 key购买 nike

创建具有大约 10 个私有(private)字段(例如 HashMap、LinkedHashMap、ArrayList 等)的类的对象的最有效干净方法是什么)。

如果我放入一个包含 10 个字段的构造函数,那看起来就像是一场噩梦。

最佳答案

您可以使用 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();

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

关于java - 构造具有许多私有(private)集合字段的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18250986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com