一、Java单例设计模式的分类
在Java中单例设计模式,可以分为懒汉式和饿汉式,代码实现分别如下:
/*饿汉式代码*/
public class Sington {
//将构造函数私有,避免外部创建对象
privateSington() {
}
//创建实例化对象
private static Sington sington = new Sington();
//返回实例对象
public static Sington getSington() {
return sington;
}
}
/*懒汉式代码*/
public class Sington {
//将构造函数私有,避免外部创建对象
private Sington() {
}
//创建实例化对象
private static Sington sington = null;
//返回实例对象
public synchronized static Sington getSington() {
if (sington != null) {
return sington;
} else {
sington = new Sington();
return sington;
}
}
} 二、结论及建议 (1)上面两种代码都能完成相同的功能,不同的是,懒汉式需要用synchronized来保证线程的安全性,和第一种比较来说,需要消耗更多的资源
(2)通过查看Runtime类源码发现,其设计为单例模式,并且用的是饿汉式,源码如下: 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() {} (3)通过以上分析,可知,饿汉式优于懒汉式,所以在开发过程中,我们建议使用饿汉式。
|