java - 使用不可变的享元跳过多余的验证

标签 java constructor immutability flyweight-pattern

我有一个看起来像这样的不可变类:

final class Foo {
  private final String name;
  private final MutableObject mo;

  public Foo(String name, MutableObject mo) {
    mo = mo.clone();
    if(!Foo.testValidity(mo)) // this test is very expensive
      throw new IllegalArgumentException();

    this.name = name;
    this.mo = mo;
  }

  public Foo bar(Foo that) {
    return new Foo(this.name, that.mo);
  }
}

bar 方法通过混合两个现有 Foo 对象的内部结构返回一个 Foo 对象。因为 MutableObject 已经在 Foo 对象中,所以保证它是有效的并且不需要复制或验证(构造函数当前这样做)。

因为验证(可能还有克隆?)很昂贵,所以我想尽可能避免它们。最好的方法是什么?这是我想出的:

final class Foo {
  private final String name;
  private final MutableObject mo;

  public Foo(String name, MutableObject mo) {
    this(name, mo, VerificationStyle.STRICT);
  }

  private Foo(String name, MutableObject mo, VerificationStyle vs) {
    if(vs == VerificationStyle.STRICT) {
      mo = mo.clone();
      if(!Foo.testValidity(mo)) // this test is very expensive
        throw new IllegalArgumentException();
    }

    this.name = name;
    this.mo = mo;
  }

  public Foo bar(Foo that) {
    return new Foo(this.name, that.mo, VerificationStyle.LENIENT);
  }

  private static enum VerificationStyle { STRICT, LENIENT; }
}

我认为,至少,它会比使用虚拟参数更干净/更清晰,并且比交换顺序更不容易出错,但是有没有更好的方法来做到这一点?这通常如何实现?

最佳答案

也许完全隐藏构造函数并使用类似工厂的方法创建新实例,例如:

  private Foo(String name, MutableObject mo) {
    this.name = name;
    this.mo = mo;
  }
  public Foo bar(Foo that) {
    return new Foo(this.name, that.mo);
  }
  public static Foo create(String name, MutableObject mo) {
    mo = mo.clone();
    if(!Foo.testValidity(mo)) // this test is very expensive
      throw new IllegalArgumentException();
    return new Foo(name, mo);
  }

关于java - 使用不可变的享元跳过多余的验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35283155/

相关文章:

java - 如何用Java检测打印机是否连接到您的计算机?

java - 如何检测 Java 类路径中缺失符号的使用情况

c++ - 没有合适的默认构造函数可用

java - 日历构造函数 Java toString

java - GCM 未在 Android 4.0.4 设备上接收消息

java - SearchView 语音监听器

java - 避免使用 if 语句创建对象

java - 当服务器返回错误时,使用 Immutables 进行改造会引发运行时异常

C++:构造和初始化顺序保证

javascript - 我想通过另一个数组中的 id 过滤出一个对象数组