2

将 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领域可以是最终的?

4

1 回答 1

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()这应该是非常安全的,因为构造函数将被设为私有,因此除非您创建自己的静态工厂方法,否则不应在不通过方法路径的情况下创建实例,在这种情况下您可以做同样的事情。

于 2015-11-21T07:39:52.517 回答