Design Patterns (.NET)- Singleton Method Part-3
Singleton method allows only one instance to be created of a singleton class at a time and then provide global access through the application.
Visual Diagram:
As you can see in the above diagram, different clients (NewObject a, NewObject b and NewObject n) trying to get the singleton instance. Once the client gets the singleton instance then they can invoke the methods (Method 1, Method 2, and Method n) using the same instance
The Advantages of using the Singleton Design Pattern in C# are as follows.
The following are the implementation guidelines for using the singleton design pattern in C#.
Example of the Singleton Design Pattern using C#
Let us understand the Singleton Design pattern in C# with an example. There are many ways, we can implement the Singleton Design Pattern in C# are as follows.
Implementational Example:
namespace SingletonDem
{
????public sealed class Singleton
????{
????????private static int counter = 0;
????????private static Singleton instance = null;
????????public static Singleton GetInstance
????????{
????????????get
????????????{
????????????????if (instance == null)
????????????????????instance = new Singleton();
????????????????return instance;
????????????}
????????}
????????
????????private Singleton()
????????{
????????????counter++;
????????????Console.WriteLine("Counter Value " + counter.ToString());
????????}
????????public void PrintDetails(string message)
????????{
????????????Console.WriteLine(message);
????????}
????}
}
namespace SingletonDemo
{
????class Program
????{
????????static void Main(string[] args)
????????{
????????????Singleton fromTeachaer = Singleton.GetInstance;
????????????fromTeachaer.PrintDetails("From Teacher");
????????????Singleton fromStudent = Singleton.GetInstance;
????????????fromStudent.PrintDetails("From Student");
????????????Console.ReadLine();
????????}
????}
}