开发者

Singleton classes

Is there any difference between a Singleton class and a class with all static members (i.e. methods and attributes).

I could not find any instance where 'all static member class' would not achieve the same functionality as class properly implementing Singleton pattern?

For eg. java.lang.Runtime is a proper Singleton class whereas java.la开发者_运维问答ng.System has all static method for access and merely has a private constructor to avoid external construction . Does anybody know why classes like Runtime are made Singleton and not implemented like java.lang.System.

Is it merely because it would be a cleaner design (i.e. mimics an object more realistically) or is there some performance benefit here?


Yes, there's a difference - a singleton can implement an interface.

Also, what looks like a singleton from the outside can actually be implemented via different classes, where the singleton access method (e.g. Runtime.getRuntime()) can create the right instance at execution time. I'm not saying that's what's happened here, but it's an option.


Well you can serialize and unserialize an object (and thus a Singleton) using the Serializable interface (on Java), but not a static class.


A singleton is instantiated once.

A static class is never instantiated.


I believe there is no difference between what you call a singleton and a class with all static methods/members in principle. In fact, I think that creating a class with all static members is a way of implementing the singleton idiom. Well, maybe in Java there is some kind of serious difference, but I'm speaking from the C++ point of view.


I think you should ask what's different between final class with private constructor and static class. Because singleton is a class and implementation depends on programmer who programs this class. It's same as ask what's differences between an object and static class.


A class can be extended to create another singleton (e.g. for testing purposes), or non-singleton class. static methods cannot be overidden, they can only be hidden in a sub class.


A common use for singletons with lazy initialization (aka Meyers singletons) is to control the order of static objects initialization (which, in C++, is undefined across different translation units). In this respect, singletons just behave like global objects, but whose order of construction behaves well.

It becomes quite difficult to control the order of destruction though. If you must rely on the singletons being destructed in some particular order (eg. a singleton logging class which should outlast other singleton instances), see Alexandrescu's book to witness the difficulty.


The primary purpose for singletons cited by the GoF is to provide a polymorphic service, where the singleton is an abstract base class, and the concrete type is decided at runtime. And, of course, there must only be one of them in the program.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜