Singleton lazy vs eager instantiation

前端 未结 5 1490
暗喜
暗喜 2020-12-07 18:51

If a singleton is implemented as follows,

class Singleton {
    private static Singleton instance = new Singleton();

    public static Singleton getInstance         


        
5条回答
  •  被撕碎了的回忆
    2020-12-07 19:42

    You may call any other static methods or static member variable too to load the singleton instance.

    class Logger {     
       private static Logger instance = new Logger(); 
       public static String LOG_LINE_SEPERATOR =  
          System.getProperty("line.separator");
       public static Logger getInstance() {  
              return instance;     
       } 
    
       public static String logPattern() {
           return null;
       }
    } 
    

    ...

    Logger.LOG_LINE_SEPERATOR; // load Logger instance or
    Logger.logPattern(); // load Logger instance
    

提交回复
热议问题