How to make an immutable singleton in Java?

后端 未结 4 1773
后悔当初
后悔当初 2021-01-19 01:26

An immutable object is initialized by its constuctor only, while a singleton is instantiated by a static method. How to make an immutable singleton in Java?

4条回答
  •  有刺的猬
    2021-01-19 02:03

    The solution pointed out by Sean is a good way of initializing singletons if their creation is not expensive. If you want to "lazy loading" capability, look into the initialization on demand holder idiom.

     // from wikipedia entry
     public class Singleton {
    
       // Private constructor prevents instantiation from other classes
       private Singleton() {
       }
    
       /**
        * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
        * or the first access to SingletonHolder.INSTANCE, not before.
        */
       private static class SingletonHolder { 
         public static final Singleton INSTANCE = new Singleton();
       }
    
       public static Singleton getInstance() {
         return SingletonHolder.INSTANCE;
       }
    
     }
    

提交回复
热议问题