With his design patttern we allways get the same instance, as you can see next.
- The Singleton class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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: