gpt4 book ai didi

java - java中final字段初始化的问题: avoiding duplication of code using multiple constructors

转载 作者:行者123 更新时间:2023-12-01 21:34:23 26 4
gpt4 key购买 nike

我有一个带有一些私有(private)最终字段的类:

public class ClassA {
private final Object field1;
private final Object field2;
...
}

该类有几个不同的构造函数,带有各种参数:

public ClassA(Object arg1, Object arg2);
public ClassA(int arg1, String arg2, boolean arg3);

这些构造函数计算要放入最终字段的值。

理想情况下,我想做这样的事情:

public ClassA(Object arg1, Object arg2) {
... // error check params
Object value1 = ... // calculate value 1 based on args
Object value2 = ... // calculate value 2 based on args

init(value1, value2);
}

public ClassA(int arg1, String arg2, boolean arg3) {
... // error check params
Object value1 = ... // calculate value 1 based on args
Object value2 = ... // calculate value 2 based on args

init(value1, value2);
}

private void init(Object arg1, Object arg2) {
... // error checks on combination of calculated arg1 and arg2 values
... // in reality there are more than 2 args, and this logic is fairly complex
field1 = arg1;
field2 = arg2;
... // other common initialization code, depends on field1 and field2
}

为了重用分配和公共(public)初始化代码。但是,由于这些字段是最终字段,因此只能在构造函数调用中对其进行赋值。

在这种情况下无法摆脱使用公共(public)构造函数来创建对象,因此任何类型的工厂方法都是不可能的。最好将对 arg1、arg2 值的组合错误检查保留在与将它们分配给 ClassA 字段的同一 block 中。否则,我会将 init() 分成 2 个函数,一个对最终字段进行预分配,一个对最终字段进行后分配,并使我的构造函数如下所示:

public ClassA(int arg1, String arg2, boolean arg3) {
... // error check params
Object value1 = ... // calculate value 1 based on args
Object value2 = ... // calculate value 2 based on args

preinit(value1, value2); // error checks combination of values
field1 = value1;
field2 = value2;
postinit(); // other common initialization code
}

建议?有什么方法可以避免这种情况,或者我是否坚持拆分 init() 函数?

最佳答案

首先,我会尝试查看构建器模式,但如果您坚持将其作为构造函数并且字段应该是最终的,请使用私有(private)构造函数:

public class ClassA {
private final Object field1;
private final Object field2;

public ClassA(Object arg1, Object arg2) {
this(calc1(arg1, arg2), calc2(arg1, arg2), true);
}

public ClassA(int arg1, String arg2, boolean arg3) {
this(calc1(arg1, arg2, arg3), calc2(arg1, arg2, arg3), true);
}

private ClassA(Object arg1, Object arg2, boolean a) {
field1 = arg1;
field2 = arg2;
}

private static Object calc1(int arg1, String arg2, boolean arg3) {
return ... // calculate value 1 based on args
}

private static Object calc2(int arg1, String arg2, boolean arg3) {
return ... // calculate value 2 based on args
}

private static Object calc1(Object arg1, Object arg2) {
return ... // calculate value 1 based on args
}

private static Object calc2(Object arg1, Object arg2) {
return ... // calculate value 2 based on args
}

}

关于java - java中final字段初始化的问题: avoiding duplication of code using multiple constructors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3362947/

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