作者LPH66 (IWH68S0XZ8M89)
看板Programming
标题Re: [问题]请问这样的 Java Class 算不算是一个 Si …
时间Thu Jan 10 01:26:35 2008
※ 引述《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)
1F:推 oohay:解释得好 59.112.227.50 01/10 01:50