看板 java 關於我們 聯絡資訊
※ 引述《qweqweqweqwe (啪)》之銘言: : 各位板友好,最近遇到了一個跟 Singleton? 有關的問題想請教一下, : 程式碼是憑印象大略打的,所以有誤的話還請見諒 QQ : class Single { : private Single mInstance; : public static Single getInstance() { : if (mInstance == null) { : mInstance = new Single(); : } : return mInstance; : } 靜態方法呼叫類別的非靜態成員? 程式編譯應該過不了 : private Single(){} : public void reset() { : mInstance = null; : } : } reset 沒加 static 修飾詞,單例應該也沒辦法實現了吧.... NPE 是什麼意思? 我不太懂你是遇到什麼多執行緒問題 如果你是希望在有人 reset 之後呼叫 getInstance 的執行緒不會得到過時的物作 那你可以這樣寫 public class SingletonTest { private static SingletonTest instance = null; public synchronized static SingletonTest getInstance(){ if ( instance == null ){ instance = new SingletonTest(); return instance; } return instance; } private SingletonTest(){ } public synchronized static void reset(){ instance = new SingletonTest(); } } 不需要額外創造一個 SYNC 物件然後在它上面同步, 同歩在類別的方法上就可以了 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.167.102.112
qweqweqweqwe:不好意思 的確是我少打,mInstance跟reset()都必須 12/29 20:28
qweqweqweqwe:加上 static沒錯,等等馬上修改文章內容 QQ 12/29 20:30