A singleton is a class which allows one instance of itself to be created and allow you to easily access to that instance. A singleton just gives you a single instance of a class. When you need a class that has only one instance. Singleton ensures you that a class has only one instance and also you have a global point to access that instance. This a simple example of a singleton pattern.
public class ThreadSafeSingleton { private static volatile ThreadSafeSingleton _instance; private static readonly object Sync= new Object(); private ThreadSafeSingleton() { } public static ThreadSafeSingleton Instance { get { if (_instance == null) { lock (Sync) { if (_instance == null) { _instance = new ThreadSafeSingleton(); } } } return _instance; } } }
The benefit of implementing Singleton:
- Ensuring that all objects access the single instance.
- The class has the flexibility to change the instantiation process.
- By changing in one instance you can change all instances of a class.
Read these articles for complete information
- http://www.yoda.arachsys.com/csharp/singleton.html
- http://csharpindepth.com/articles/general/singleton.aspx