Re: [問題] 什麼時候該用getInstance()?
※ 引述《psalter (Regular Expression)》之銘言:
: 關於 B.getInstance();
: 其實可以參考 Factorty Pattern,
: 將建構子封裝起來有許多好處,包括
: (1)可以控制instance的數量,作 Multiton
: (2)管理取得此物件的權限:public, protected, default
: 因此不一定是需要作Singleton時才可應用 getInstance()
: 當然,與Factory不太一樣,這裡是直接call物件本身的getInstance method
呃, factory method 沒有規定生出來的都要是同一個東西
在 singleton 要求是大家得到的都是同一份
所以宣告 instance 時會這樣寫
final static Instance inst;
(多一個 final 一多生您就知道了 xd)
並且為了保證在 multi-threads 下 getInstance 不會冒出不同的
instance 來, 會一開始就建立好 instance
final static Instance inst = new Instance();
或是在 getInstance() 加上 sync 的關鍵字
REF.
http://en.wikipedia.org/wiki/Singleton_pattern
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 220.128.219.202
※ 編輯: qrtt1 來自: 220.128.219.202 (03/13 11:45)
推
03/15 19:35, , 1F
03/15 19:35, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 5 之 6 篇):