What is Singleton Design Patterns?

1/12/2020 7:21:50 AM

Singleton Pattern: Singleton Pattern belongs to creational type pattern. This pattern is used when we need to ensure that only one object of a particular class need to be created. All further references to the objects are referred to the same underlying instance created. Now given bellow the code and explain the code:

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Reflection;
using testForClass1;
namespace testFor
    public sealed class Singleton
        private static int count = 0;
        private static Singleton instance = null;
        public static Singleton GetInstance { get { if (instance == null) { instance = new Singleton(); } return instance; } }

        public Singleton()
            Console.WriteLine("Count : " + count);

        public void PrientDetals()
            Console.WriteLine("I am from Singleton class");

    public class Program
        static void Main(string[] args)
            Singleton sing = Singleton.GetInstance;
            Singleton sing2 = Singleton.GetInstance;
            Singleton sing3 = Singleton.GetInstance;
            Singleton sing4 = Singleton.GetInstance;

In this code we create a class name as Singleton. This class have PrientDetals method. This method responsible to print the text. Now when we call the method first create the instance of the class but every time create instance when we call the method. Now make the class is sealed and create static property Which is create the   instance and we can get the method without every time create instance it’s called Singleton Pattern.