让我们定义一个类,这样,多个实例变量就只能像这样的类一样懒惰地初始化一次:public class MyClass {
private Object myLazyField;
private Integer anotherLazyField;
public Object getMyLazyField() {
if (myLazyField == null) {
synchronized (this) {
if (myLazyField == null) {
myLazyField = new Object();
}
}
}
return myLazyField;
}
public Integer getAnotherLazyField() {
if (anotherLazyField == null) {
synchronized (this) {
if (anotherLazyField == null) {
anotherLazyField = 10;
}
}
}
return anotherLazyField;
}
}
代码很丑陋,并且初始化的结构是重复的。
我的问题是:如何简化延迟初始化,以避免结构重复?
我尝试过:class Utility {
public static T init(Object object, T initialValue, Supplier supplier) {
synchronized (object) {
if (initialValue == null) {
return supplier.get();
}
}
return initialValue;
}
}
以及MyClass:public Object getMyLazyField() {
if (myLazyField == null) {
myLazyField = Utility.init(this, myLazyField, Object::new);
}
return myLazyField;
}
更好,但是我仍在寻找使用函数式编程的更好解决方案。