1、餓漢式
package singleton;
/**
* 餓漢式單例
* @author 蔣明原
*
*/
public class HungrySingleton {
/**jvm保證instance只被初始化一次*/
private static HungrySingleton instance = new HungrySingleton();
/**阻止外部使用new實例化對象*/
private HungrySingleton(){
}
/**
* 獲取實例
* @return 唯一的instance
*/
public static HungrySingleton getInstance() {
return instance;
}
}
2、懶漢式
package singleton;
/**
* 懶漢式單例
* @author 蔣明原
*
*/
public class LazySingleton {
/**
* 阻止外界使用new實例化對象
*/
private LazySingleton() {
}
/**
* 只有在調用getInstance()時此類才會被裝載
* 在SingletonKerriganF.Java中說明了加載順序
*/
private static class SingletonHolder {
/**
* 對象實例,jvm保證只初始化一次
*/
static final LazySingleton INSTANCE = new LazySingleton();
}
/**
* 獲取實例
* @return 返回唯一實例
*/
public LazySingleton getInstance() {
return SingletonHolder.INSTANCE;
}
}
3、懶漢式單例內部類加載順序 (來自http://www.Javaeye.com/topic/575052)
package singleton;
/**
* 實現單例訪問Kerrigan的第六次嘗試
* @author IcyFenix
* @see http://www.Javaeye.com/topic/575052
*/
public class SingletonKerriganF {
private static String arg = null;
private static class SingletonHolder {
/**
* 單例對象實例
*/
static final SingletonKerriganF INSTANCE = new SingletonKerriganF();
}
public static SingletonKerriganF getInstance() {
return SingletonHolder.INSTANCE;
}
public SingletonKerriganF() {
System.out.println("Kerrigan get arg:" + getArg());
System.out.println("Kerrigan created!");
}
public static String getArg() {
return arg;
}
public static void setArg(String arg) {
SingletonKerriganF.arg = arg;
}
public static void main(String[] args) {
System.out.println("SingletonKerriganF was loaded,but SingletonKerriganF$SingletonHolder don't");
SingletonKerriganF.setArg("this maybe some config files etc....");
SingletonKerriganF.getInstance();
}
}