Design Pattern->Creational Pattern->Singleton.

The singleton pattern is a design pattern that restricts the Instantiation of a class to one object. It can be used as a global variable. It can be serialized for later purpose. I haven't seen any project without Singleton class.

There are many ways to write Singleton class. Here I will be giving a simple implementation in C# as well as Theradsafe.

Class: SingleTon.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.ComponentModel;

using System.Threading;

namespace SingleTonSample

{

sealed class SingleTon

{

private static SingleTon single = new SingleTon();

int myUniqueKey = 0;

public int UniqueKey()

{

return Interlocked.Increment(ref myUniqueKey);

}

public static SingleTon Instance

{

get { return single; }

}

private SingleTon(){ }

public void PrintMe()

{

Console.WriteLine("Singleton Class Testing");

}

}

}

Class: Program.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace SingleTonSample

{

class Program

{

static void Main(string[] args)

{

SingleTon.Instance.PrintMe();

int Value = SingleTon.Instance.UniqueKey();

Console.WriteLine("Unique Value =" + Value);

}

}

}