关于静态支架单例模式 [英] Regarding static holder singleton pattern

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

问题描述

我已经在很多方面开发了单例,这取决于像易失性/懒惰单例,急切单例,普通单例和通过Enum这样的条件,但具体我想知道下面显示的静态持有者模式单例。

I have developed singleton in many ways depending upon the condition like volatile/lazy singleton, eager singleton, normal singleton and through Enum also, but specifically I want to know about static holder pattern singleton shown below.

public static class Singleton {
    private static class InstanceHolder {
        public static Singleton instance = new Singleton();
    }

    private Singleton(){}

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

请告知哪些条件有利,哪些是什么它的好处。

Please advise under which conditions it is beneficial and what are its benefits.

推荐答案

这种模式至少有三个原因:

This pattern is beneficial for at least 3 reasons:


  1. 静态工厂

  2. 延迟初始化

  3. 线程安全

JVM推迟初始化InstanceHolder类,直到实际使用它为止,并且因为使用静态初始化程序初始化Singleton,所以不需要额外的同步。任何线程对 getInstance 的第一次调用都会导致InstanceHolder被加载和初始化,此时Singleton的初始化通过静态初始化器发生。

The JVM defers initializing the InstanceHolder class until it is actually used, and because the Singleton is initialized with a static initializer, no additional synchronization is needed. The first call to getInstance by any thread causes InstanceHolder to be loaded and initialized, at which time the initialization of the Singleton happens through the static initializer.

静态支架模式也被认为是双重检查锁定反模式的最明智的替代品。

Static holder pattern is also considered as the smartest replace for Double-check-locking antipattern.

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

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