将AutoValue与Builder模式一起使用时,如何在构造函数中初始化其他自定义最终字段?
示例
@AutoValue
abstract class PathExample {
static Builder builder() {
return new AutoValue_PathExample.Builder();
}
abstract String directory();
abstract String fileName();
abstract String fileExt();
Path fullPath() {
return Paths.get(directory(), fileName(), fileExt());
}
@AutoValue.Builder
interface Builder {
abstract Builder directory(String s);
abstract Builder fileName(String s);
abstract Builder fileExt(String s);
abstract PathExample build();
}
}
在现实世界中,初始化(比如在`fullPath字段中)更昂贵,所以我只想做一次。我看到了两种方法:
1)延迟初始化
private Path fullPath;
Path getFullPath() {
if (fullPath == null) {
fullPath = Paths.get(directory(), fileName(), fileExt());
}
return fullPath;
}
2)建设者的初始化
private Path fullPath;
Path getFullPath() {
return fullPath;
}
@AutoValue.Builder
abstract static class Builder {
abstract PathExample autoBuild();
PathExample build() {
PathExample result = autoBuild();
result.fullPath = Paths.get(result.directory(), result.fileName(), result.fileExt());
return result;
}
是否有其他选择,以便fullPath
字段可以最终?
答案 0 :(得分:1)
您可以使用一个Builder方法,该方法采用完整路径并使用默认值:
@AutoValue
abstract class PathExample {
static Builder builder() {
return new AutoValue_PathExample.Builder();
}
abstract String directory();
abstract String fileName();
abstract String fileExt();
abstract Path fullPath();
@AutoValue.Builder
interface Builder {
abstract Builder directory(String s);
abstract Builder fileName(String s);
abstract Builder fileExt(String s);
abstract Builder fullPath(Path p);
abstract PathExample autoBuild();
public PathExample build() {
fullPath(Paths.get(directory(), fileName(), fileExt()));
return autoBuild();
}
}
}
这应该是非常安全的,因为构造函数将被设置为私有,因此除非您创建自己的静态工厂方法,否则不应该通过build()
方法路径创建实例的情况,其中你可以做同样的事情。