手寫一個簡單的單例

懶漢式

/**
*懶漢式
*/
public class Singleton{
	private static Singleton singleton = new Singleton();
	private Singleton(){}
	public static Singleton getSingleton(){
		return singleton;
	}
}

餓漢式

/**
* 餓漢式
*/
public class Singleton{
	private static Singleton singleton = null;
	private Singleton(){}
	public static synchronized Singleton getSingleton(){
		if(singleton==null){
			singleton = new Singleton();
		}
		return singleton;
	}
}
相關文章
相關標籤/搜索