685
99.9
May 16, 2010
Singleton Pattern is a creational pattern and is all about making sure we have only one instance (maximum) of a class at any given point in time.
It just needs a private constructor so that none of the external instances can directly create an instance of the singleton class under consideration. This Singleton class needs to expose one public method eg: GetInstance, which intenally calls the private constuctor only if there is no preexisting instance of the class. Lock statements can be used in the implementation to avoid any hassles of multi-threaded access to the Singleton.
1,128
99.9
May 17, 2010
Some differences between Singletons and Static classes are...
* Singletons can implement interfaces
* You cannot pass a static class as a parameter to a method, this can be done with a Singleton
* A Singleton is a normal class that is instantiated just once, a static class is never instantiated
UPDATE
As a side note, I usually tend not to use either of these. Instead I use my DI container (Ninject, StructureMap, ...) to supply me with a singleton of the required type when needed.