我刚刚在某个地方看到了下面的代码:
public class SingletonObjectDemo {
private static SingletonObjectDemo singletonObject;
// Note that the constructor is private
private SingletonObjectDemo() {
// Optional Code
}
public static SingletonObjectDemo getSingletonObject() {
if (singletonObject == null) {
singletonObject = new SingletonObjectDemo();
}
return singletonObject;
}
}
我需要知道这部分的意义是什么:
if (singletonObject == null) {
singletonObject = new SingletonObjectDemo();
}
如果我们不使用这部分代码会怎样?仍然会有一个
SingletonObjectDemo
的单例对象,那么为什么我们还需要这段代码呢?