Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Implementing Singleton in C#

    • 0
    • 3
    • 2
    • 0
    • 0
    • 0
    • 0
    • 0
    • 295
    Comment on it

    Hello Friends,
    This blog explains how to implement singleton design pattern in c#. So lets start with few basic things:--


    What is Singleton ?

    A singleton is a class which only allows one instance of itself to be created - and gives simple, easy access to instance.They fall in to the Creational patterns categories.


    What does Singleton Offer ?

    The Singleton pattern restricts the class to be instantiated only once and has a global point of access. In other words you can say class is static but can be instantiated.

    Instance Control:- Singleton creates only one instance and prevents any further copies, and ensure that all object access the single instance.

    Flexibility:- In singleton class controls the instantiation process.

    Parameters:- Singleton class can be used as parameters or objects.


    How it can be implemented ? You need to follow these steps to create a singleton pattern.

    • Declare a static object variable.
    • Declare private constructor to avoid new object creation.
    • Declare a public property which can be accessed outside of the class.
    • Instantiate an object and assign it to the private variable.

      Example:- If you are designing a logging system then only one instance of logger is required to handle the log requests coming from different sources.

    public class Singleton
    {
       private static Singleton instance ; //Private static object declaration 
    
       //Private construction declaration for prevent object creation  
      private Singleton ()
      {
      }
    
       //A public property to access outside of the class to create an object 
       public static Singleton Instance
       {
         get
         {
             if(instance==null)
             {
                    instance= new Singleton();
             }
             return instance;
          }
       }
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: