Singleton lazy vs eager instantiation [英] Singleton lazy vs eager instantiation

查看:146
本文介绍了Singleton lazy vs eager instantiation的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果单个实现如下,

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

    public static Singleton getInstance() {
        return instance;
    }
}

这种实现与延迟初始化方法有何不同?
在这种情况下,实例将在加载类时创建,并且类本身仅在第一次活动使用时加载(例如,Singleton.getInstance(),而不是在声明例如Singleton singleton = null时; )

How is this implementation different from the lazy initialization approach? In this case,the instance will be created when the class is loaded and the class itself is loaded only on the first active use (for example, Singleton.getInstance() not when you declare for instance Singleton singleton = null;)

即使使用延迟初始化方法,也会在调用getInstance()时创建实例

Even with lazy initialization approach, the instance is created on the call to getInstance()

Am i在这里遗漏了什么?

Am i missing something here?

推荐答案

您也可以调用任何其他静态方法或静态成员变量来加载单例实例。

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

这篇关于Singleton lazy vs eager instantiation的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆