Singleton v/s class with static members & methods in Java

Possible Duplicate:
Difference between static class and singleton pattern?

Why would one ever require one and only one instance? Same purpose can be achieved using classes with static member variables and static methods.

As far as I can find out, there might be two possible answers to it -

  • When your class needs to have state and you want only one object of it. From the design point of view, class with static methods & variables are considered to be the Utility classes and shouldn't be keeping any state.

  • If your class needs to take part in polymorphism and you want only one object of the class(es) which are in the inheritance tree.

  • It would be really helpful if someone can provide an example from real life scenario or from any Java API where Singleton objects need to participate in Polymorphism / Inheritance?


    Collections.emptySet() is a typical example of a singleton that can't be implemented as a static class since, obviously, its goal is to be an instance of the java.util.Set interface. It's not costly to create, but it would be stupid to create a new instance each time an empty set is needed, since the unique instance can be reused.


    Classes that perform logging or common access to data bases frequently follow the Singleton pattern. Basically anything that should have instance methods and that is costly to construct.


    Scope and behavior are different concerns and should NOT be mixed. You may want your object to be available per use, per thread, per web request, per session or global (Singleton). The reasons for making these adjustments are likely due to resource management and ultimately performance. The behavior inside your class shouldn't have to change if you change its scope.

    Singleton is pattern for taking a regular object and controlling its scope with just a little bit of bolt-on code. Ideally though, you really shouldn't really deal with scope at all inside your object and delegate that to a factory or container.

    链接地址: http://www.djcxy.com/p/78828.html

    上一篇: 单身类与静态方法和字段?

    下一篇: Singleton v / s类,带有Java中的静态成员和方法