The singleton pattern is used in almost all modern day programming languages, so why do I keep finding it written incorrectly in so many applications, so lets start with the right way
public sealed class SimpleNoLockLazy
{
static readonly SimpleNoLockLazy instance = new SimpleNoLockLazy();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static SimpleNoLockLazy()
{
}
SimpleNoLockLazy()
{
}
public static SimpleNoLockLazy Instance
{
get
{
return instance;
}
}
}
So why this implementation? The reason for using a Singleton is for performance in a multi-threaded environment and this pattern is not only simple, but it is the fastest. I have attached a benchmark application, which is based on Jon Skeet’s benchmark, but testing using a Parallel processes.
I found Jon Skeet’s article very useful