现在的位置: 首页 > 综合 > 正文

Head First设计模式-单例模式

2013年02月14日 ⁄ 综合 ⁄ 共 564字 ⁄ 字号 评论关闭

一、整体代码

        Singleton.java

public class Singleton {
	private static Singleton uniqueInstance;
 
	// other useful instance variables here
 
	private Singleton() {}
 
	public static synchronized Singleton getInstance() {
		if (uniqueInstance == null) {
			uniqueInstance = new Singleton();
		}
		return uniqueInstance;
	}
 
	// other useful methods here
}

        Singleton.java

public class Singleton {
	private static Singleton uniqueInstance = new Singleton();;
 
	// other useful instance variables here
 
	private Singleton() {}
 
	public static Singleton getInstance() {
		return uniqueInstance;
	}
 
	// other useful methods here
}

 

二、解析

      1、第一种单件模式,在多线程时需要同步,造成了额外开销。

       2、第二种不用同步。


抱歉!评论已关闭.