單例模式
簡介:
? 單例模式為了節(jié)省系統(tǒng)資源,把一個實例化的資源不回收,想用直接調(diào)用就可以,節(jié)省了創(chuàng)建和回收的過程,提高了系統(tǒng)開發(fā)的效率
線程安全:
? 多線程下要保證被實例化一次
高性能:
延遲加載:
有七種
餓漢式
class King {
private static final King kingInstance = new King();
static King getInstance() {
return kingInstance;
}
private King() {
}
}
/**
*1.線程安全性保證: private static final King kingInstance = new King();
*JVM 加載class時有一個ClassLoader有一個主動加載和被動加載 new SIngleton01()主動加載<clinit>
*在編譯階段把所有的賦值操作記入到里面)///只能運行一次保證了同步///
*/
(private:外界調(diào)用不了)
懶漢式
class king {
private Test() {
}
public static Test instance = null;
public static Test getInstance() {
if (instance == null) {
//多個線程判斷instance都為null時,在執(zhí)行new操作時多線程會出現(xiàn)重復情況
instance = new Singleton2();
}
return instance;
}
}
/**
*1.單線程安全多線程不安全
*在編譯階段把所有的賦值操作記入到里面)///只能運行一次保證了同步///
*2.性能: 用的時候?qū)嵗挥玫臅r候為空 性能比懶漢式好
*3延遲加載:延遲加載
*/