單例模式有兩種:一種是:餓漢式 一種是:懶漢式
餓漢式如下:
class Person {
//1.私有化構造器
private Person(){
}
//2.私有化對象
private static Person instance = new Person();
//3.提供給外部訪問的方法
public static Person getInstance(){
return instance;
}
}
懶漢式:可能存在線程安全問題,一般情況下,不建議使用
class Zoo {
private Zoo(){
}
private static Zoo instance = null;
public static Zoo getInstance(){
if(instance == null){
instance = new Zoo();
}
return instance;
}
}