Java单例模式的各种写法(Initialization on Demand Holder模式)

来源:互联网 发布:ubuntu界面太小 编辑:程序博客网 时间:2024/04/30 20:53

Initialization on Demand Holder模式,这种方法使用内部类来做到延迟加载对象,在初始化这个内部类的时候,JLS(Java Language Sepcification)会保这个类的线程安全(the class initialization phase is guaranteed by the JLS to be serial)
这种写法最大的美在于,完全使用了Java虚拟机的机制进行同步保证,没有一个同步的关键字。

public class Singleton    {        private static class SingletonHolder        {            public final static Singleton instance = new Singleton();        }           public static Singleton getInstance()        {            return SingletonHolder.instance;        }    } 

其他写法见原文地址:

http://blog.sina.com.cn/s/blog_75247c770100yxpb.html

0 0