日期:2013-02-28  浏览次数:20478 次

Implementing the Singleton Pattern in C#
view auther's website

The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. Most commonly, singletons don't allow any parameters to be specified when creating the instance - as otherwise a second request for an instance but with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter, the factory pattern is more appropriate.) This article deals only with the situation where no parameters are required. Typically a requirement of singletons is that they are created lazily - i.e. that the instance isn't created until it is first needed.

There are various different ways of implementing the singleton pattern in C#. I shall present them here in reverse order of elegance, starting with the most commonly seen, which is not thread-safe, and working up to a fully lazily-loaded, thread-safe, simple and highly performant version. Note that in the code here, I omit the private modifier, as it is the default for class members. In many other languages such as Java, there is a different default, and private should be used.

All these implementations share four common characteristics, however:

A single constructor, which is private and parameterless. This prevents other classes from instantiating it (which would be a violation of the pattern). Note that it also prevents subclassing - if a singleton can be subclassed once, it can be subclassed twice, and if each of those subclasses can create an instance, the pattern is violated. The factory pattern can be used if you need a single instance of a base type, but the exact type isn't known until runtime.
The class is sealed. This is unnecessary, strictly speaking, due to the above point, but may help the JIT to optimise things more.
A static variable which holds a reference to the single created instance, if any.
A public static means of getting the reference to the single created instance, creating one if necessary.
Note that all of these implementations also use a public static method GetInstance as the means of accessing the instance. In all cases, the method could easily be converted to a property with only an accessor, with no impact on thread-safety or performance.

First version - not thread-safe
public sealed class Singleton
{
static Singleton instance=null;
Singleton()
{
}
public static Singleton GetInstance()
{
if (instance==null)
instance = new Singleton();
return instance;
}
}


As hinted at before, the above is not thread-safe. Two different threads could both have evaluated the test if (instance==null) and found it to be true, then both create instances, which violates the singleton pattern. Note that in fact the instance may already have been created before the expression is evaluated, but the memory model doesn't guarantee that the new value of instance will be seen by other threads unless suitable memory barriers have been passed.

Second version - simple thread-safety
public sealed class Singleton
{
static Singleton instance=null;
static readonly object padlock = new object();
Singleton()
{
}
public static Singleton GetInstance()
{
lock (padlock)
{
if (instance==null)
instance = new Singleton();
return instance;
}
}
}


This implementation is thread-safe. The thread takes out a lock on a shared object, and then checks whethe