gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:49:49 25 4
gpt4 key购买 nike

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

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/

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