Please go through the example at the end of this article so that you understand the Singleton Design Pattern better.

Now it's time for the Singleton Design Pattern. Here we go.

What is Singleton Design Pattern?

Ensures a class has only one instance and provides a global point of access to it.

A singleton is a class that 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, since a second request of an instance with a different parameter could be problematic! (If the same instance should be accessed for all requests with the same parameter then the factory pattern is more appropriate.)

There are various ways to implement the Singleton Pattern in C#. The following are the common characteristics of a Singleton Pattern.

A single constructor, that is private and parameterless.

The class is sealed.

A static variable that 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.

Advantages

The advantages of a Singleton Pattern are:

Singleton pattern can be implemented interfaces.

It can be also inherit from other classes.

It can be lazy loaded.

It has Static Initialization.

It can be extended into a factory pattern.

It helps to hide dependencies.

It provides a single point of access to a particular instance, so it is easy to maintain.

Disadvantages

The disadvantages of a Singleton Pattern are:

Unit testing is more difficult (because it introduces a global state into an application).

This pattern reduces the potential for parallelism within a program, because to access the singleton in a multi-threaded system, an object must be serialized (by locking).

Singleton class vs. Static methods

The following conpares Singleton class vs. Static methods:

A Static Class cannot be extended whereas a singleton class can be extended.

A Static Class can still have instances (unwanted instances) whereas a singleton class prevents it.

A Static Class cannot be initialized with a STATE (parameter), whereas a singleton class can be.

A Static class is loaded automatically by the CLR when the program or namespace containing the class is loaded.

How to Implement Singleton Pattern in your code:

There are many way to implement a Singleton Pattern in C#.

No Thread Safe Singleton.

Thread-Safety Singleton.

Thread-Safety Singleton using Double-Check Locking.

Thread-Safe Singleton without using locks and no lazy instantiation.

Fully lazy instantiation.

Using .NET 4's Lazy<T> type.

1. No Thread Safe Singleton:

Explanation of the following code:

The following code is not thread-safe.

Two different threads could both have evaluated the test (if instance == null) and found it to be true, then both creates 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.

// Bad code! Do not use!

publicsealedclassSingleton

{

//Private Constructor.

private Singleton()

{

}

privatestaticSingleton instance = null;

publicstaticSingleton Instance

{

get

{

if (instance == null)

{

instance = newSingleton();

}

return instance;

}

}

}

2. Thread Safety Singleton

Explanation of the following code:

This implementation is thread-safe.

In the following code, the thread is locked on a shared object and checks whether an instance has been created or not.

This takes care of the memory barrier issue and ensures that only one thread will create an instance.

For example: Since only one thread can be in that part of the code at a time, by the time the second thread enters it, the first thread will have created the instance, so the expression will evaluate to false.

The biggest problem with this is performance; performance suffers since a lock is required every time an instance is requested.

publicsealedclassSingleton

{

Singleton()

{

}

privatestaticreadonlyobject padlock = newobject();

privatestaticSingleton instance = null;

publicstaticSingleton Instance

{

get

{

lock (padlock)

{

if (instance == null)

{

instance = newSingleton();

}

return instance;

}

}

}

}

3. Thread Safety Singleton using Double Check Locking

Explanation of the following code:

In the following code, the thread is locked on a shared object and checks whether an instance has been created or not with double checking.

publicsealedclassSingleton

{

Singleton()

{

}

privatestaticreadonlyobject padlock = newobject();

privatestaticSingleton instance = null;

publicstaticSingleton Instance

{

get

{

if (instance == null)

{

lock (padlock)

{

if (instance == null)

{

instance = newSingleton();

}

}

}

return instance;

}

}

}

4. Thread Safe Singleton without using locks and no lazy instantiation

Explanation of the following code:

The preceding implementation looks like very simple code.

This type of implementation has a static constructor, so it executes only once per Application Domain.

It is not as lazy as the other implementation.

publicsealedclassSingleton

{

privatestaticreadonlySingleton instance = newSingleton();

// Explicit static constructor to tell C# compiler

// not to mark type as beforefieldinit

static Singleton()

{

}

private Singleton()

{

}

publicstaticSingleton Instance

{

get

{

return instance;

}

}

}

5. Fully lazy instantiation

Explanation of the following code:

Here, instantiation is triggered by the first reference to the static member of the nested class, that only occurs in Instance.

This means the implementation is fully lazy, but has all the performance benefits of the previous ones.

Note that although nested classes have access to the enclosing class's private members, the reverse is not true, hence the need for instance to be internal here.

That doesn't raise any other problems, though, as the class itself is private.

The code is more complicated in order to make the instantiation lazy.

publicsealedclassSingleton

{

privatestaticreadonlySingleton instance = newSingleton();

// Explicit static constructor to tell C# compiler

// not to mark type as beforefieldinit

static Singleton()

{

}

private Singleton()

{

}

publicstaticSingleton Instance

{

get

{

return instance;

}

}

}

6. Using .NET 4's Lazy<T> type

Explanation of the following code:

If you're using .NET 4 (or higher) then you can use the System.Lazy<T> type to make the laziness really simple.

All you need to do is pass a delegate to the constructor that calls the Singleton constructor, which is done most easily with a lambda expression.

It also allows you to check whether or not the instance has been created with the IsValueCreated property.