Whenever we want to implement a Singleton Pattern, we can always find examples by picking up a book on Design Patterns or by searching through the internet. Most of these implementations are very similar, and have been in use for some time. I have shown one such implementation that is traditionally being practiced in a multi-threaded environment.
Singleton the Traditional way:
public sealed class Singleton
{
private static volatile Singleton instance = null;
private static object syncRoot = new Object();
private Singleton() { } // Private constructor – cannot be instantiated
public static Singleton Instance()
{
if (instance == null) // Double check locking pattern
{
lock (syncRoot)
{
if (instance == null)
{
instance = new Singleton();
}
}
}
return instance;
}
}
Microsoft, on the other hand, has dramatically simplified the implementation of Singleton Pattern with enriched features in .NET. Please see below:
Singleton the .NET way:
public sealed class Singleton
{
// Private constructor – cannot be instantiated
private Singleton() { }
// .NET will initialize static property only during first call
// Framework guarantees thread safety on static type initialization
// Readonly keyword prevents Instance from being
// modified after initialization
public static readonly Singleton Instance = new Singleton();
}
I got one thing to say – “.Net Rocks”!!!!