The Singleton Design Pattern ensures that only a single instance of a given object can exist.
It does this by making the class constructor private so that it [the
singleton itself] has full control over when the class instance is
created. In order to gain access to an instance of a class that
implements the Singleton pattern, the developer must call a
shared/static method of that Singleton class.
public sealed class MySingleton
//volatile ensures that variable is fully initilized before accessing it.
private static volatile MySingleton _instance;
private static object lockObject = new object();
//private construct to avoid Newing the class
private MySingleton() { }
//double checking for multi threading
public static MySingleton Insatnce()
{
if (_instance ==null)
{
//Allows only one thread to initialise the object
lock(lockObject)
{
if (_instance==null)
_instance = new MySingleton();
}
}
return _instance;
}
Now
you will say it is like a static class what is the difference? Basic
difference is that a multithreaded environment maintains one instance
per thread where as Singleton is one across threads.
Another way of implementing the same pattern
public class Singleton
{
// A static member to hold a reference to the singleton instance.
private static Singleton instance;
//
A static constructor to create the singleton instance. Another
alternative is to use lazy initialization in the Instance property.
static Singleton()
{
instance = new Singleton();
}
// A private constructor to stop code from creating additional instances of the singleton type.
private Singleton() { }
// A public property to provide access to the singleton instance.
public static Singleton Instance
{
get { return instance; }
}
}
No comments:
Post a Comment