Sometimes we just want to have one and only instance of a class. Like a class used for logging or a class used for modifying registry settings or some configuration files. If we have more than one instance of this class we could run into a mess and confusion. To solve this we have the singleton class.

Singleton class is class which has only one instance and cannot be intantiated more than once.

Singleton classes need to be implemented as shown below.

using System;

namespace LearnCs
{
public class Singleton
{
/// <summary>
/// We have a static variable to hold a instance of this class.
/// </summary>
private static Singleton SingletonInstance;
private static object dummyObject = new object();
// Why do we need this dummyObject?? U will learn later
/// <summary>
/// A private constructor ensures that no one can instantiate this class
/// by using new keyword outside this class
/// </summary>
private Singleton()
{

}

/// <summary>
/// Get Instance method returns the one and only instance of Singleton class.
/// </summary>
/// <returns>One and only instance of Singleton</returns>
public static Singleton getSingletonInstance()
{
if(SingletonInstance == null)
SingletonInstance = new Singleton();

return SingletonInstance;
}

//Other methods corresponding to this class here
}
}

Please note that this could run into problem if multiple threads call getSingletonInstance() method for first time.

If we know that multiple threads could call this getSingletonInstance() method, then use the lock keyword in the following manner inside that function.

public static Singleton getSingletonInstance()
{
if (SingletonInstance == null)
{
//SingletonInstance = new Singleton();
// The above line should not be used if multiple threads
// are going to access this method simultaneously.
// lock makes sure that the access to this portion of code
// is synchronized by various threads.
lock (dummyObject)
{
if (SingletonInstance == null)
SingletonInstance = new Singleton();
}
}
return SingletonInstance;
}

But remember, using lock might decrease the performance of your code upto 100 times. So better avoid it, if not needed. Rather try to initialize SingletonInstance variable in the beginning itself !!

Advertisements