Is a static class a singleton?
Possible Duplicate:
Difference between static class and singleton pattern?
I was wondering,
Would a class such as Java's Math class, where all methods are static be considered a singleton? Or does a singleton have to have an instance, eg: Math.getInstance().abs(...
) to qualify as a singleton?
Thanks
Having just static methods in a class does not qualify it being a Singleton
, as you can still make as many instances of that class, if you have a public constructor
in it.
For a class to qualify as Singleton
, it should have private constructor
, so that it can't be instantiated from outside the class, and have a static factory
that returns the same instance
everytime invoked.
If you really mean static class
, then first of all, you can't have your top-level
class as static
. You can only have static nested class
, in which case you don't need to create any instance of that class, but you can and you can create multiple instances and hence it as not Singleton
.
Also, the class you mentioned - java.lang.Math
, is not a static class. You should see the documentation of that.
Static classes in Java are just nested classes which aren't inner classes. (They're not like static classes in C#, for example.) They can still have instance methods, state etc - and there can be multiple instances.
java.lang.Math
is not a static class.
And no, a class which never has an instance is not a singleton. The important difference is that a singleton can implement an interface (or even derive from an abstract class) whereas if you never create an instance of a class, any instance methods are pointless.
A class that is applied Singleton Pattern has one or none instance at any time on a JVM. That's why it's called single-ton. Having static
or non-static
members has no relationship with being singleton or non-singleton.
上一篇: 单身人士使用静态成员和方法?
下一篇: 静态类是一个单例吗?