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
    • 316
    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.

    1. public class Singleton
    2. {
    3. private static Singleton instance ; //Private static object declaration
    4.  
    5. //Private construction declaration for prevent object creation
    6. private Singleton ()
    7. {
    8. }
    9.  
    10. //A public property to access outside of the class to create an object
    11. public static Singleton Instance
    12. {
    13. get
    14. {
    15. if(instance==null)
    16. {
    17. instance= new Singleton();
    18. }
    19. return instance;
    20. }
    21. }
    22. }

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: