With his design patttern we allways get the same instance, as you can see next.
- The Singleton class:
package pt.joaobrito.singleton;
public final class Singleton {
/**
* A private constructor. This is necessary in order to not allow create a new Singleton object
* from the outside with the keyword new
*/
private Singleton() {}
private static final class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
}
public static final Singleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
2. The main class:
package pt.joaobrito.singleton;
public class Main {
public static void main(String[] args) {
Singleton s1 = Singleton.getInstance();
Singleton s2 = Singleton.getInstance();
// test if the reference are the same
System.out.println(s1 == s2);
}
}
3. The result:

