单例公共静态最终 [英] singleton public static final

查看:60
本文介绍了单例公共静态最终的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道Java中的单例.按照惯例,单例设置如下:

I've been wondering about singletons in Java. By convention, a singleton is set up something like this:

private static MyClass instance = null;
public static MyClass getInstance(){
    if (instance == null){
        instance = new MyClass();
    }
    return instance;
}
private MyClass(){}

最近我已切换为使用以下内容:

Recently I've switched to using the following:

public static final MyClass instance = new MyClass();
private MyClass(){}

这更短,更快捷,因为没有空检查,并且键入 MyClass.instance 对我来说比键入 MyClass.getInstance()更好.有什么原因不能使第二种方法成为主流方法呢?

This is a lot shorter, faster as there's no null-check, and typing MyClass.instance feels nicer to me than typing MyClass.getInstance(). Is there any reason why the second is not the mainstream way to do this?

推荐答案

第一个版本在第一次实际需要实例时创建实例,而第二个版本(较短的版本)在类已初始化

The first version creates the instance the first time it is actually needed, while the second (the shorter) runs the constructor as soon as the class is initialized

类或接口类型T将在下列任何一项的首次出现:

A class or interface type T will be initialized immediately before the first occurrence of any one of the following:

  • T是一个类,并创建T的实例.
  • T是一个类,并调用T声明的静态方法.
  • 分配了由T声明的静态字段.
  • 使用了由T声明的静态字段,并且该字段不是常量变量(第4.12.4节).
  • T是顶级类(第7.6节)和断言语句(第14.10节)词汇嵌套在T(第8.1.3节)中.[...]

调用类Class和in中的某些反射方法包java.lang.reflect也会导致类或接口初始化.

Invocation of certain reflective methods in class Class and in package java.lang.reflect also causes class or interface initialization.

首次使用时进行初始化是一种性能改进,如果构造函数中的代码进行了昂贵的操作,则可以加速应用程序的启动.另一方面,第二个版本易于阅读,并且自动具有线程安全性.

The initialization upon first usage is a performance improvement that may speed up the startup of the application if the code in the constructor makes expensive operations. On the other hand, the second version is straightforward to read and is automatically thread-safe.

无论如何,最新技术不会以任何方式创建单例:对于一堆KB,您可以获得依赖注入库,使其能够为您工作,并处理更复杂的场景(例如,查看Spring和AOP)支持的注入).

Anyway, the state of the art is not creating singleton in either ways: for a bunch of KB you can get dependency injection libraries that make it working for you, and also handle more complex scenarios (for example look at Spring and AOP-backed injection).

注意:第一个版本在粘贴的代码段中不是线程安全的

这篇关于单例公共静态最终的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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