The Singleton pattern works by restricting construction of a
class to itself, by making the constructor private.
Then a property (or method) typically called Instance
is set up to provide access to the one-and-only-one instance of the class,
which is instantiated on the first request. A UML diagram of the Singleton's
structure is shown here:
The code for the naïve implementation of the Singleton
pattern follows here. Do not use this approach in any multi-threaded
environment, including an ASP.NET application.
The problem with this implementation is that it is not
thread-safe, meaning that the check for (_instance==null) could be executed by
two separate threads before either one has instantiated _instance, thus
allowing two threads to enter the if {} block and creating two instances of the
object.
This issue can be addressed in several ways. The first is
to apply locking, but the simple, brute-force approach to locking doesn't
actually work very effectively in terms of efficiency, so as a further
optimization one tends to arrive at double-check locking, which works (though
not in Java 1.5 or earlier) but is rather complex and very easy to get wrong.
A somewhat simpler approach is to rely on .NET's lazy type
instantiation and implement the Instance through the use of a nested class.
This approach is shown here:
Note that the static constructor for Nested() is required,
in order to ensure the CLR does not mark the nested type with a flag called beforefieldinit. You can read more about why
this is important in Jon Skeet's
excellent article on Singletons, which is where the above LazySingleton
pattern comes from.