我最近爱上了延迟加载技术,其用法如下:
public class SomeClass
{
static class ComplexClassHolder
{
static ComplexClass complex = new ComplexClass(); // takes a long time
}
static double someMethod(int x, int y)
{
return ComplexClassHolder.complex.calculate(x,y);
}
public double quickMethod() // if only this method is called there is no initialization of the instance of ComplexClass
{
return 1.0+1.0;
}
}
但类似的技术是否也适用于非静态方法?
示例
import java.util.Random;
public class SomeClass
{
final int seed;
public SomeClass(int seed)
{
this.seed=seed;
}
class ComplexClassHolder
{
Random r = new Random(SomeClass.this.seed); // let's pretend this takes a long time
}
public double randomDouble()
{
return ComplexClassHolder.r.nextDouble();
}
}
问题是以上是不可能的,因为ComplexClassHolder和ComplexClassHolder.r不是静态的。但是,如果我将它们设为静态,我将无法访问 SomeClass.this.seed。
我知道我可以使用 getInstance() 和同步来做到这一点,但如果静态情况下可能的优雅技术也能以某种方式在这里使用,我将不胜感激。
最佳答案
对于有经验的程序员来说,您认为“优雅”的东西看起来既困惑又愚蠢。
当您查看以下示例时,您会发现没有由语言或类加载器规范引起的隐式副作用。它所做的一切都在您看到的代码中。你也明白,诡计并不美。
public synchronized double getNextDouble() {
if (r == null) {
r = new Random();
}
return r.nextDouble();
}
您可能还会意识到,如果您爱上了一把锤子,您所有的问题都会开始看起来像钉子。 :)
关于非静态方法的 Java 惰性初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10297896/