search

Home  >  Q&A  >  body text

java - 使用IoDH的单例模式写法,静态内部类的instance变量是否一定需要声明成final的?

方式一:

public class Singleton {
    private Singleton() {
    }

    private static class LazyHolder {
        private static final Singleton INSTANCE = new Singleton();
    }

    public static Singleton getInstance() {
        return LazyHolder.INSTANCE;
    }
}

一般而言,这种方式见得最多的写法是static final,那么final是否是必须的呢?
多个线程调用静态方法getInstance()时,JVM也只会加载和初始化内部类一次,将静态变量INSTANCE定义不可变的final是否必须?
在wikipedia的页面中,采取的是方式一:Initialization-on-demand holder idiom

阿神阿神2767 days ago530

reply all(2)I'll reply

  • 怪我咯

    怪我咯2017-04-18 10:35:52

    After adding final, it becomes mutable. There is no other difference.
    A better approach for Singleton is to use Enum (see Effective Java for details).

    reply
    0
  • 阿神

    阿神2017-04-18 10:35:52

    No difference, declare private,其它类也无法直接访问(反射除外)。如果担心反射访问,就如楼上说的用Enumto create a singleton.

    reply
    0
  • Cancelreply