I have the following code:
package DesignPatterns;
public class SingletonProblem
{
public static void main(String[] args) {
System.out.println(BillPughSingleton.getInstance());
System.out.println(BillPughSingletonWithoutContainer.getInstance());
}
}
class BillPughSingletonWithoutContainer
{
private static BillPughSingletonWithoutContainer instance = new BillPughSingletonWithoutContainer();
static {
System.out.println("Static is now loaded in BillPughSingletonWithoutContainer");
}
private BillPughSingletonWithoutContainer() {}
public static BillPughSingletonWithoutContainer getInstance()
{
return instance;
}
}
class BillPughSingleton
{
private static class Container
{
public static BillPughSingleton instance = new BillPughSingleton();
}
private BillPughSingleton() {}
public static BillPughSingleton getInstance()
{
return Container.instance;
}
}
The output is:
DesignPatterns.BillPughSingleton@36baf30c
Static is now loaded in BillPughSingletonWithoutContainer
DesignPatterns.BillPughSingletonWithoutContainer@5ca881b5
Why is the container useful if, in the example without the container, the instance also seems to be lazily loaded when the BillPughSingletonWithoutContainer.getInstance()
is called?
In eagerly loading (what the BillPughSingletonWithoutContainer is claimed to be), I expected the output to be:
Static is now loaded in BillPughSingletonWithoutContainer
DesignPatterns.BillPughSingleton@36baf30c
DesignPatterns.BillPughSingletonWithoutContainer@5ca881b5
Instead of:
DesignPatterns.BillPughSingleton@36baf30c
Static is now loaded in BillPughSingletonWithoutContainer
DesignPatterns.BillPughSingletonWithoutContainer@5ca881b5
So in other words what is the benefit (in Java) of using the container?