概念
單例模式:是一種對(duì)象創(chuàng)建型模式,用來(lái)確保程序中一個(gè)類(lèi)最多只有一個(gè)實(shí)例,并提供訪問(wèn)這個(gè)實(shí)例的全局點(diǎn)。
單例模式的解決方案
- 隱藏類(lèi)的構(gòu)造方法,用private修飾符修飾構(gòu)造方法.
- 定義一個(gè)public的靜態(tài)方法(getInstance()) ,返回這個(gè)類(lèi)唯一靜態(tài)實(shí)例。
雙重檢查的單例模式
public class Singleton {
private volatile Singleton instance = null;
public Singleton getInstance() {
if (instance == null) {
synchronized(this) {
if (instance == null) {
instance = new Singleton();
}
}
}
return instance;
}
}
關(guān)鍵字volatile 保證多線程下的單例:原因:https://blog.csdn.net/shadow_zed/article/details/79650874
原理:https://blog.csdn.net/anjxue/article/details/51038466?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-2.control
推薦方法:
public class Singleton {
private Singleton () {};
static class SingletonHolder {
static Singleton instance = new Singleton();
}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
}