Difference between a singleton and a static class
3 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Kedar_Khanvilkar
Posted On:   Thursday, June 21, 2001 09:27 AM

hi everyone,


I wanted to know the difference between singleton and a static class.
Is there a comparison at all between the two, if yes why and if not why?


Thanks in advance,




Kedar Khanvilkar

Re: Difference between a singleton and a static class

Posted By:   Thiru_Kumar  
Posted On:   Wednesday, August 8, 2001 05:54 PM

Re: Difference between a singleton and a static class

Posted By:   Ryan_Breidenbach  
Posted On:   Wednesday, June 27, 2001 10:03 AM

In Java, there really is not a big differnce between the two. Even Sun waffled on picking one over the other. Both the System and Runtime classes need to have exactly one instance, but the System class uses all static methods while the Runtime class behaves like a Singleton.


One difference is that if you need exactly one instance of a class and you want that class to implenent an interface, you must use a Singleton since interfaces cannot have static methods. Another difference is that using the Singleton pattern allows you to control exactly how many instances of a class get created, allowing you to create exactly five or exactly two instances of class if that is what you want. However, this can also be accomplished by using the Factory Method pattern, but that is another topic...


As for performance, neither will have resources allocated to them unless/until they are used. The Singleton's instance will not be created (presumably) until the getInstance method is called. The all-static class will not be loaded until one of its methods is called.


Finally, this pattern is not nearly as useful in Java as it is in other OO languages. For example, I believe that in SmallTalk, all methods must belong to an object, so Singleton's are necessary to create exactly one instance when needed. In Java, as we know, we can circumvent this by creating a class with all static methods and attributes.


Hope this helps.

Re: Difference between a singleton and a static class

Posted By:   D_Srinivasan  
Posted On:   Friday, June 22, 2001 06:54 AM

The concrete difference is that you have far greater control over the "singletonness" with a singleton. You can seamlessly convert a singleton so that its behaviour is to return a new instance every time.

The second difference is that a static is initialized at the start of your "program". A singleton can be made to perform lazy instantiation. For more detail take a look at Gamma et al

/D

About | Sitemap | Contact