Photo Gallery

Friday, October 5, 2018

Design Pattern - Singleton Pattern

In this post, I will explain how to create or implement singleton design pattern using c#. This pattern provides best way to create an object. This singleton class provides object which can be available without instantiate the object of the class.



Development :

1) Create a Singleton Class

public sealed class Singleton
{
public static int counter = 0;
// Threadsafety
private static readonly object obj = new object();
private static Singleton instance = null;
// public property is used to return only one instance of the class leveraginmg on the private property.
public static Singleton GetInstance
{
get
{
if (instance == null) // Double chcked null as lock is very expensive to use
{
lock (obj)
{
if (instance == null)
instance = new Singleton();
}
}
return instance;
}
}
// private constructor used to prevent the class to instantiate multiple times.
private Singleton()
{
counter++;
Console.WriteLine("Number of Instanace created : " + counter.ToString());
}
public void PrintDetails(string message)
{
Console.WriteLine("Messsage from the Method :{0}", message);
}
}
view raw Singleton.cs hosted with ❤ by GitHub
2) Get the Singleton Object

public class Program
{
static void Main(string[] args)
{
//Singleton Demo
Parallel.Invoke(
() => sc1(),
() => sc2()
);
Console.ReadLine();
}
private static void sc1()
{
Singleton sc1 = Singleton.GetInstance;
sc1.PrintDetails("Invoked First Method");
}
private static void sc2()
{
Singleton sc2 = Singleton.GetInstance;
sc2.PrintDetails("Invoked Second Method");
}
}
view raw Program.cs hosted with ❤ by GitHub
3) Check the output ( Number of Instance should be 1 )



If you have any questions, post here. Also, provide your valuable suggestions and thoughts in form of comments in the section below.

Thank you !!!

No comments:

Post a Comment