一、概念
一个类只有一个对象。
注意:
对于单例模式,我们需要注意并不一定要在类加载的时候就产生对象,这样会影响性能。比如单例模式的实现中的饿汉模式,此模式中单例在类加载之时就产生了,可是万一这个对象需要消耗很多资源呢?所以建议在需要创建时,才创建对象。
二、应用场景
当一个类只需要存在它的一个对象时,可以选择。
对于单例,需要注意两点
- 什么时候对对象进行初始化(类加载时/真正需要对象时)
- 线程问题。多线程环境下也要保证只有一个类的实例。
- 加锁会影响性能。如果每次获取对象,都有一个加锁操作,会非常影响性能。其实只有在第一次创建单例对象时才需要加锁,以后获取单例对象时就不需要加锁了。
三、java源码中单例模式的应用
说道单例模式,自然就想到了它的最简单的两种实现——懒汉模式、饿汉模式。然而,单例模式还有其他实现,如双重锁定检查、volatile。为了避免重复造轮子,请参考 单例模式、双检测锁定DCL、volatile详解
在jdk中应用,java.lang.Runtime就利用了单例模式。
/**
* Every Java application has a single instance of class
* <code>Runtime</code> that allows the application to interface with
* the environment in which the application is running. The current
* runtime can be obtained from the <code>getRuntime</code> method.
* <p>
* An application cannot create its own instance of this class.
*
* @author unascribed
* @see java.lang.Runtime#getRuntime()
* @since JDK1.0
*/
public class Runtime {
private static Runtime currentRuntime = new Runtime();
/**
* Returns the runtime object associated with the current Java application.
* Most of the methods of class <code>Runtime</code> are instance
* methods and must be invoked with respect to the current runtime object.
*
* @return the <code>Runtime</code> object associated with the current
* Java application.
*/
public static Runtime getRuntime() {
return currentRuntime;
}
/** Don't let anyone else instantiate this class */
private Runtime() {}
}
正如注释所说,每一个java应用程序都有一个Runtime实例。Runtime的单例模式是采用饿汉模式创建的,意思是当你加载这个类文件时,这个实例就已经存在了。
Runtime类可以取得JVM系统信息,或者使用gc()方法释放掉垃圾空间,还可以使用此类运行本机的程序。具体参考 Java常用类库——Runtime类
spring Mvc 中的controller 默认是单例模式的,解析
spring mvc Controller单例解析
四、参考文献
单例模式、双检测锁定DCL、volatile详解
Double-checked Locking (DCL) and how to fix it (ctd)
Java常用类库——Runtime类