Effective Java》中给出了一种精妙Singleton的解决方法,充分利用了Java虚拟机的特性
-
publicclassSingleton{
-
-
-
-
privatestaticclassSingletonHolder{
-
-
staticfinalSingletonuniqueInstance=newSingleton();
-
-
}
-
-
privateSingleton(){
-
-
-
-
}
-
-
publicstaticSingletongetInstance(){
-
-
returnSingletonHolder.uniqueInstance;
-
-
}
-
-
-
-
}
When the getInstance method is invoked for the first time, it reads SingletonHolder.uniqueInstance for the first time, causing the SingletonHolder class to get initialized.The beauty of this idiom is that the getInstance method is not synchronized and performs
only a field access, so lazy initialization adds practically nothing to the cost of access. A modern VM will synchronize field access only to initialize the class.Once the class is initialized, the VM will patch the code so that subsequent access to the field
does not involve any testing or synchronization.
分享到:
相关推荐
一个大牛写的控制重复播放的单例类,使用的时候直接包含使用单例的方法就可以解决 多视图叠加播放的问题
单例类只能有一个实例。 单例类必须自己创建自己的唯一实例。 单例类必须给所有其他对象提供这一实例。 Singleton模式包含的角色只有一个,就是Singleton。Singleton拥有一个私有构造函数,确保用户无法通过new直接...
简单的单例模式举例Singleton 分为恶汉式 懒汉式
四种常见的单例: 1、没有构造函数(DEFINE_SINGLETON_DEFAULT); 2、有构造函数,构造函数没有参数(DEFINE_SINGLETON_CONSTRUCT_NO_PARAM); 3、有构造函数,构造函数有没有参数版本(DEFINE_SINGLETON_...
Java面向对象(高级)-- 单例(Singleton)设计模式
单例模式(Singleton Pattern)是 Java 中最简单的设计模式之一。这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式。 这种模式涉及到一个单一的类,该类负责创建自己的对象,同时确保只有单个...
单例模式(Singleton)
单例模式 Singleton 单例模式线程安全问题和拓展
NULL 博文链接:https://wy649898543.iteye.com/blog/1431908
在Java应用中,单例对象能保证在一个...3、有些像交易所的核心交易引擎,控制着交易流程,如果该类可以创建多个的话,系统完全乱了,只有使用单例模式,才能保证核心交易服务器独立控制整个流程。 CSDN代码的详细解释。
主要介绍了单例模式 Singleton 简单实例设计模式解析的相关资料,需要的朋友可以参考下
设计模式C++学习之单例模式(Singleton)
该文当中对Java单类模式有非常细致入微的,循序渐进的讲解。
单例模式(Singleton)的6种实现
一个产生随机数的例子,整个应用程序中只需要一个类的实例来产生随机数,客户端程序从类中获取这个实例,调用这个实例的方法nextInt(),公用的方法访问需要进行同步,这是单例模式需要解决的同步问题。
java Singleton单例模式 java Singleton单例模式
单例设计模式Singleton1
此示例展示了Qml 的单例模式(类似全局对象,只生成一次实例,可全局使用) surfsky.cnblogs.com
深入浅出Singleton,详细掌握单例模式