單例模式
只需要一個實(shí)例的場合,可以使用單例模式,如何日志處理,緩存,連接池,讀取配置文件等場合。
餓漢模式
加載類時,就實(shí)例化
public class SingleTon{
//1.將構(gòu)造方法私有化,不允許外部直接創(chuàng)建對象
private Singleton(){
}
//2.創(chuàng)建類的唯一實(shí)例,使用private static修飾
private static Singleton instance = new Singleton();
//3.提供一個用于獲取實(shí)例的方法,使用public static修飾
public static Singleton getInstance(){
return instance;
}
}
懶漢模式
需要類時,再進(jìn)行實(shí)例化
public class SingleTon{
//1.將構(gòu)造方法私有化,不允許外部直接創(chuàng)建對象
private Singleton(){
}
//2.創(chuàng)建類的唯一實(shí)例,使用private static修飾
private static Singleton instance ;
//3.提供一個用于獲取實(shí)例的方法,使用public static修飾
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton;
}
return instance;
}
}