Re: [問題]請問這樣的 Java Class 算不算是一個 Si …
※ 引述《fourdollars (四元)》之銘言:
: ※ 引述《LPH66 (IWH68S0XZ8M89)》之銘言:
: : 個人以為這不是Singleton
: : 因為從頭到尾你的class連一個instance都沒有出現過
: : 只是利用了static的共有性質達成目的
: : ---
: : 以下節錄英文維基: ( http://en.wikipedia.org/wiki/Singleton_pattern )
: : Note the distinction between a simple static instance of a class and a
: : singleton: although a singleton can be implemented as a static instance,
: : it can also be lazily constructed, requiring no memory or resources until
: : needed. Another notable difference is that static member classes cannot
: : implement an interface, unless that interface is simply a marker.
: : 第一點是說這種class可以在要用到時才佔空間 (即沒用到就不佔)
: : 而static實作的則是一開始就佔空間了
: 可是下面這行就是在初始的狀態下不佔空間啊... @_@a
: private static Process process = null;
: 另外 waitForTermination() 裡面也有 process = null;
這裡說的不是instance 而是這個class本身
注意它不只說不佔記憶體 它是說 "requiring no memory or resources until needed"
以java來說你可以把它寫成讓classloader會在用到時才把它載入
而static class的話無論如何classloader會在一開始就把它載入了
(維基那頁下面有個這樣的範例)
: : 第二點說的是用static實作的不能實作任何"有東西的"interface
: : 這裡"有東西的"的意思是這個interface要求要實現某些成員函式
: : 但是用static實作的卻不能有任何成員函式 只能有靜態(static)函式
: Java 裡面的 class function 也可以當做 member function 來使用~ @_@a
: SingletonProcess tmp;
: tmp.runCommand("dir");
: tmp.waitForTermination();
話說一般的Singleton不會寫成這樣吧...
它所謂不能實作"有東西的"interface的意思是
那些interface裡定義了實作它的人該要有某些member method
而你的class裡只能有static method
(而這是因為你必然得要用SingletonProcess.runCommand("dir");這種方式呼叫
這使得runCommand必然得是個static method)
舉個和你寫的很像的東西的好了: java.lang.Math
它不是Singleton 但其他方面卻和你寫的東西很像:
呼叫時要用 Math.abs(value); Math.pow(a,b); 等等
而它的這些所有method都是static
當然 就如你所說它也能這樣用:
Math mymath;
c=mymath.pow(a,b);
但這正表明了Math這個class不是一個Singleton
: 還是不懂為何不能算是 Singleton ... @_@a
重新看過一次你的code之後
最根本的問題應該是:
你的class能夠隨時產生實體
而能夠隨時產生實體的class最一開始就不是Singleton了
就如同java.lang.Math的例子一樣 它也不是個Singleton
(維基那頁開宗明義就說了 "the singleton pattern is a design pattern
that is used to restrict instantiation of a class to one object.")
--
'Oh, Harry, dont't you see?' Hermione breathed. 'If she could have done
one thing to make absolutely sure that every single person in this school
will read your interview, it was banning it!'
---'Harry Potter and the order of the phoenix', P513
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 140.112.250.80
※ 編輯: LPH66 來自: 140.112.250.80 (01/10 01:27)
推
01/10 01:50, , 1F
01/10 01:50, 1F
討論串 (同標題文章)
本文引述了以下文章的的內容:
完整討論串 (本文為第 3 之 16 篇):