Singleton Design Pattern with example in c#.net


Singleton Design Pattern


Singleton Design Pattern will come to picture, whenever we can instantiate a class once and make sure that that instance should available through out the code. A design pattern which support only one time instantiation is called Singleton Design Patterns.

In this we are using private constructor for the singleton class. So, we cann't create object as well we can't extend class. At this time, we will use public static method for creating a instance of the object. In the public static method we will use lazy instantiation concept.

Some of the people will confuse what is the difference between Singleton and static.

Example:

  1. While accessing resources in the shared environment. 
  2. For doing logging records in our application, we will instantiate logging class only once.
  3. For any important configuration classes.


In the multithreading environment we have to take special care of the object because multiple threads will access the same instance at a time. This may cause deadlock situation while application running.

Abstract Factory, Factory method and prototype design patterns also implemented as Singletons

Example:
  class Program
    {
        static void Main(string[] args)
        {
            SingletonTest logFile = SingletonTest.returnInstanc();
            logFile.strCode = "http://aspnettutorialonline.blogspot.com/";
            //int i = 1;
            Console.WriteLine(logFile.strCode);
            Console.ReadLine();
        }
    }

    class SingletonTest
    {
        private static SingletonTest singletonTest = null;

        private string strcode = string.Empty;

        private SingletonTest()
        {
            strcode = string.Empty;
        }

        public static SingletonTest returnInstanc()
        {
            //lazy initialization
            if (singletonTest == null)
                singletonTest = new SingletonTest();
            return singletonTest;
        }

        public string strCode
        {
            get { return strcode; }
            set { strcode = value; }
        }
    }


For thread safety implementation please go through this article.


If you have any queries or suggestions, please fell free to ask in comments section.
Share this post :

Post a Comment

Please give your valuable feedback on this post. You can submit any ASP.NET article here. We will post that article in this website by your name.

 
Support : Ranga Rajesh Kumar
Copyright © 2012. ASP.NET Examples - All Rights Reserved
Site Designed by Ranga Rajesh Kumar