網(wǎng)上關(guān)于單例模式的講解鋪天蓋地,而這個(gè)設(shè)計(jì)模式在開發(fā)中用的頻率也比較頻繁,所以說說這個(gè)。
單例模式,顧名思義,通過這個(gè)模式構(gòu)建出的對(duì)象在整個(gè)項(xiàng)目的運(yùn)行中有并且只有只一個(gè),且對(duì)象不變。具體怎么做呢
public class Appcontext {
//在創(chuàng)建最初就new一次,僅僅一次
private static final Appcontext appcontext = new Appcontext();
//私有方法,不讓外部去訪問
private Appcontext() {
}
//通過這個(gè)方法去返回給調(diào)用者唯一對(duì)象
public static Appcontext getAppcontext() {
return appcontext;
}
}
這種寫法被稱之為餓漢模式,既然有餓漢模式就有懶漢模式
public class Appcontext {
//在創(chuàng)建最初就new一次,僅僅一次
private static Appcontext appcontext = new Appcontext();
//私有方法,不讓外部去訪問
private Appcontext() {
}
//通過這個(gè)方法去返回給調(diào)用者唯一對(duì)象
public static Appcontext getAppcontext() {
if (appcontext == null) {
appcontext = new Appcontext();
}
return appcontext;
}
}
這就是餓漢模式,但是缺有線程不安全的情況發(fā)生,比如線程A運(yùn)行到了
appcontext = new Appcontext();
剛剛進(jìn)入,但是還沒有new
線程B執(zhí)行到了
if (appcontext == null) {
此時(shí)appcontext確實(shí)是==null的,然后2秒(隨便說的2秒)過后,你的項(xiàng)目就存在了2個(gè)對(duì)象。刺激吧=w=
所以我這里還是推薦第一種寫法。
單例模式是用的最廣泛而且最簡(jiǎn)單的一種單例模式了,使用的時(shí)候注意一下,如果你用單例模式構(gòu)建一個(gè)對(duì)象去存儲(chǔ)一個(gè)東西,那么這個(gè)對(duì)象是不會(huì)銷毀的,除非你手動(dòng)釋放資源。不然可能會(huì)發(fā)生內(nèi)存泄露的事情。!!!!要注意!!!