定義:一個(gè)類有且僅有一個(gè)實(shí)例,并且自行實(shí)例化向整個(gè)系統(tǒng)提供
應(yīng)用:像Windows的任務(wù)管理器阿宅,做網(wǎng)站訪問次數(shù)統(tǒng)計(jì)(當(dāng)一個(gè)類需要頻繁應(yīng)用銷毀操作時(shí)單例比較適合)
優(yōu)點(diǎn):節(jié)約內(nèi)存;限制了實(shí)例的個(gè)數(shù)势告,有利于Java垃圾回收
懶漢式:延遲加載没佑,省資源,不加同步鎖可能造成并發(fā)务漩,加同步鎖訪問處理效率變慢(推薦使用靜態(tài)內(nèi)部類)
public class Singleton {
private static Singleton singleton;
private Singleton() {
}
public static synchronized Singleton getSingleton() {
if (singleton == null) {
singleton = new Singleton();
}
return singleton;
}
}
②餓漢式:線程安全墨状,多個(gè)線程進(jìn)行訪問時(shí)不會(huì)實(shí)例化多個(gè)對(duì)象;
缺點(diǎn)是無論是否用到該實(shí)例都會(huì)被初始化菲饼,無故的開銷變大
public class Singleton2 {
private static Singleton2 singleton2 = new Singleton2();
private Singleton2() {
}
public static Singleton2 getsingleton2() {
return singleton2;
}
}