Static and Singleton classes seem to provide very similar functionality from what I can see. Can someone tell me what the differences are and in what situation each would be better suited?
Steve
Last edited by Frinavale; Apr 8 '10, 01:38 PM.
Reason: Moved from ASP.NET to Software Development
Singleton is a pattern that you can implement so that only one instance of the class is ever used.
It is a Static (Shared in VB.NET) class but it implements the Singleton Pattern.
A class that implements the Singleton Pattern does not have a public constructor (just a private one). It has a method that lets the calling code access the single instance of the class that exists (if it doesn't exist, this method will instantiate an instance of itself so that the calling class can get a reference to it).
See Wiki: Singleton Pattern...it does a better job of explaining than me :)
So is there any general rule of thumb to dictate when I should choose to use the Singleton design pattern over the Static class? And are there any performance differences between the two options?
So is there any general rule of thumb to dictate when I should choose to use the Singleton design pattern over the Static class? And are there any performance differences between the two options?
I think it's a matter of convenience and flexibility. With a static class, I think just about every attribute in the class needs to be static as well. I don't tend us use static classes, except for a place to store methods, so I'm not 100% on this.
With Singleton, you don't need to make every attribute static, so it may fit better with the rest of your classes, since it's really an object just like any other object, but only with the restriction that there can be only one instance.
"If" you discover that you need more than one instance, for load balancing or resource sharing or such, the Singleton can change into a Multiton quite easily; whereas, a static class cannot.
However, the singleton does have to be concerned with multiple threads, which static classes do not.
Singletons are basically just a big global variable and if used incorrectly that can make for some difficult to track down bugs in your program. In my experience I used Singletons for logging information. One benefit of using a Singleton verses a Static class is that a Static class will always allocate memory where as a Singleton will only require memory to be allocated if it is used.
Comment