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

Skipping superfluous verification with immutable flyweights

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

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 方法 returns 通过混合两个现有 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; }
}

我认为至少比使用虚拟参数 cleaner/clearer 并且比交换顺序更不容易出错,但是有没有更好的方法来做到这一点?这通常是如何完成的?

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

  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);
  }