單例模式有懶漢和餓漢模式,代碼就不在此贅述了。懶漢模式會帶來線程安全的問題,是以一般采用餓漢模式。從java的源代碼中也可看出應該選擇餓漢模式。
public class runtime {
private static runtime currentruntime = new runtime();
public static runtime getruntime() {
return currentruntime;
}
private runtime() {}
.......
}
這就是典型的餓漢單例模式。是以在選擇的時候一般選用餓漢模式。