Development :
1) Create a Singleton Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
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