我有一个包含很多字段的 JAVA 类。它们基本上应该在构造函数阶段设置并且永远不会改变。从语义上讲,这个类是一个不可变的。
public class A{
final int a;
final short b;
final double e;
final String f;
final String g;
//and more
}
问题是这些字段通常都有默认值,因此我不想总是让用户负担所有这些字段的构造函数。大多数时候,他们只需要设置几个。有几种方法可以解决这个问题:
- 我需要很多不同签名的构造函数。
- 为这些字段创建一堆set方法,只设置那些非默认值。但这以某种方式表明了与不可变性质不同的语义。
- 创建一个新的可变参数类并将该类用作构造函数。
这些都不是完全令人满意的。还有其他方法吗?谢谢。 一种方式
最佳答案
我会结合使用参数类和流畅的构建器 API 来创建参数:
public class A {
private final int a;
private final short b;
private final double e;
private final String g;
public static class Aparam {
private int a = 1;
private short b = 2;
private double e = 3.141593;
private String g = "NONE";
public Aparam a(int a) {
this.a = a;
return this;
}
public Aparam b(short b) {
this.b = b;
return this;
}
public Aparam e(double e) {
this.e = e;
return this;
}
public Aparam g(String g) {
this.g = g;
return this;
}
public A build() {
return new A(this);
}
}
public static Aparam a(int a) {
return new Aparam().a(a);
}
public static Aparam b(short b) {
return new Aparam().b(b);
}
public static Aparam e(double e) {
return new Aparam().e(e);
}
public static Aparam g(String g) {
return new Aparam().g(g);
}
public static A build() {
return new Aparam().build();
}
private A(Aparam p) {
this.a = p.a;
this.b = p.b;
this.e = p.e;
this.g = p.g;
}
@Override public String toString() {
return "{a=" + a + ",b=" + b + ",e=" + e + ",g=" + g + "}";
}
}
然后像这样创建 A 的实例:
A a1 = A.build();
A a2 = A.a(7).e(17.5).build();
A a3 = A.b((short)42).e(2.218282).g("fluent").build();
A类不可变,参数可选,接口(interface)流畅。
关于 "immutable class"的 Java 构造函数具有许多具有默认值的字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11378932/