所謂的單例模式是指單個實例
單例模式的實現需要以下兩個步驟
單例類示例
餓漢式單例代碼
package com
/**
* @author TaoistWar
*
*/
public class Singleton {
//
private static Singleton singleton = new Singleton();
//
private Singleton() {
}
//
public static Singleton getInstance() {
return singleton;
}
}
懶漢式單例代碼
package com
/**
*
* @author TaoistWar
*
*/
public class LazySingleton {
//
private static LazySingleton singleton;
//
private LazySingleton() {
}
//
public synchronized static LazySingleton getInstance() {
if (singleton == null) {
singleton = new LazySingleton();
}
return singleton;
}
}
比較
餓漢式單例
懶漢式單例
結論
因為在我們的開發中
From:http://tw.wingwit.com/Article/program/Java/gj/201311/27268.html