public class SingletonObject
{
private SingletonObject()
{
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it’s ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

private static SingletonObject ref;
}

lazy
public class SingletonObject
{
private SingletonObject()
{
}

public static SingletonObject getSingletonObject()
{
if (ref == null)
// it’s ok, we can call this constructor
ref = new SingletonObject();
return ref;
}

private static SingletonObject ref;
}

The difference between your code and the “sample code” is that your singleton is instantiated when the class is loaded, while in the “sample” version, it is not instantiated until it is actually needed.

Advertisements