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