- 要點(diǎn)
- 某個(gè)類只能有一個(gè)實(shí)例
- 必須自行創(chuàng)建實(shí)例
- 必須向整個(gè)系統(tǒng)提供這個(gè)實(shí)例
- 優(yōu)點(diǎn)
- 在內(nèi)存中只有一個(gè)對象恋博,節(jié)省內(nèi)存空間
- 避免頻繁的創(chuàng)建、銷毀對象匈挖,提高性能
- 避免對共享資源的多重占用
- 缺點(diǎn)
- 擴(kuò)展比較困難
- 如果實(shí)例化的對象長期不利用稠氮,系統(tǒng)將默認(rèn)為垃圾進(jìn)行回收,造成對象狀態(tài)丟失
- 實(shí)現(xiàn)
- 只提供私有的構(gòu)造方法
- 含有一個(gè)該類的靜態(tài)私有對象
- 提供一個(gè)靜態(tài)的公有方法用于創(chuàng)建茉盏、獲取靜態(tài)私有對象
- 方案
- 懶漢式:對象創(chuàng)建過程中實(shí)例化
//懶漢式:類內(nèi)實(shí)例對象創(chuàng)建時(shí)并不直接初始化鉴未,直到第一次調(diào)用get方法時(shí),才完成初始化的操作
// 時(shí)間換空間
public class SingletonTwo {
// 1.創(chuàng)建私有構(gòu)造方法
private SingletonTwo() {
}
// 2.創(chuàng)建靜態(tài)的該類實(shí)例對象
private static SingletonTwo instance = null;
// 3.創(chuàng)建開發(fā)的靜態(tài)方法提供實(shí)例對象
public static SingletonTwo getInstance() {
if (instance == null)
instance = new SingletonTwo();
return instance;
}
}
- 餓漢式:靜態(tài)公有方法中實(shí)例化
//餓漢式:創(chuàng)建對象實(shí)例的時(shí)候直接初始化 空間換時(shí)間
public class SingletonOne {
// 1.創(chuàng)建類中私有構(gòu)造
private SingletonOne(){}
// 2.創(chuàng)建該類型的私有靜態(tài)實(shí)例
private static SingletonOne instance=new SingletonOne();
// 3.創(chuàng)建共有靜態(tài)方法返回靜態(tài)實(shí)例對象
public static SingletonOne getInstance(){
return instance;
}
}
Test
public class SingtonTest {
public static void main(String[] args) {
SingletonOne one = SingletonOne.getInstance();
SingletonOne two = SingletonOne.getInstance();
System.out.println(one);
System.out.println(two);
System.out.println("=========================");
SingletonTwo one1 = SingletonTwo.getInstance();
SingletonTwo two1 = SingletonTwo.getInstance();
System.out.println(one1);
System.out.println(two1);
}
}
-使用場景:
- 創(chuàng)建對象時(shí)占用資源過多鸠姨,但同時(shí)又需要用到該類對象
- 對系統(tǒng)資源要求統(tǒng)一讀寫铜秆,如讀寫配置信息
- 當(dāng)多個(gè)實(shí)例存在可能引起程序邏輯錯(cuò)誤,如號碼生成器