Singleton Design Pattern in C#


HTML clipboard

Design Patterns provide solutions to common recurring problems. Design patterns can be classified as creational, structural or behavioral .Singleton and Factory patterns are two of the creational pattern.Here we will discuss these two patterns .In the later posts we will discuss other design patterns.

Singleton Design Pattern

We use this design pattern when we want to restrict the number of instances of any object to one at max at any instant of time. The practical implementation of this design pattern can be seen in applications that we use daily. Take the example of Microsoft word .What happens when you open multiple word documents and navigate between them?. There is only one instance of the word application active at a time ,you can verify this by checking the active processes .So all the requests for handling the different word documents is handled by a single application instance.

Here is an implementation of the singleton design pattern in C#. We will use a console application for this example. We will create a class and define a private constructor in that class so that the instances of that class can be created from only within that class.

       private Singleton()
        {

        }

Since we declare our class constructor as shown above we can not access it from outside the class .The below statement will give compilation error

     Singleton obj = new Singleton(); 

To access the single object of the Singleton class we will create a static variable of type Singleton and a property to access that private variable.

Here is the complete source code of the above example :

   class Singleton
    {
        private Singleton()
        {

        }
        //private static variable of Singleton type.
        private static Singleton objSingle = new Singleton();

        //declare a public static property that returns the
        //Singleton object as we can not call the private
        //constructor from outside the class.
        public static Singleton ObjSingle
        {
            get { return Singleton.objSingle; }
            set { Singleton.objSingle = value; }
        }

        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
 
    }
    class Program
    {

        static void Main(string[] args)
        {
            //the below line create an object of singleton type
            Singleton objFirstObject = Singleton.ObjSingle;
            objFirstObject.Name = "ashish";
            //if we access the objSingle property from another variable we will get the same object
            Singleton objSecondObject = Singleton.ObjSingle;
            //We have assigned the name in first object,we will get the same value in second object since both points
            //to the same instance
            Console.WriteLine("objFirstObject.Name={0} ,objSecondObject.Name={1}",objFirstObject.Name,objSecondObject.Name);
            Console.ReadLine();
        }

    }

Factory Method Pattern

In the Factory method pattern there is Factory method which decides which subclass to instantiate depending on the information passed by the client. All the subclasses implement a common interface.

The client declares a variable of interface type and calls the Factory method that returns an instance of the subclass to the client code.So the client is decoupled from the implementation details of subclass creation.

Following is an example of factory method pattern.

        interface IGreet
        {
            string Hello();
        }
 
        class WeekStart : IGreet
        {
            public string Hello()
            {
                return " Week Started";
            }
        }
 
        class WeekEnd : IGreet
        {
            public string Hello()
            {
                return "Happy Weekend";
            }

        }
        class Creator
        {
            public IGreet FactoryMethod()
            {
                if (DateTime.Now.DayOfWeek == DayOfWeek.Monday || DateTime.Now.DayOfWeek == DayOfWeek.Tuesday
                || DateTime.Now.DayOfWeek == DayOfWeek.Wednesday || DateTime.Now.DayOfWeek == DayOfWeek.Thursday
                )
                    return new WeekStart();
                else
                    return new WeekEnd();
            }
        }

        class Program
        {
            private DateTime dt = DateTime.Now;

            static void Main(string[] args)
            {
                Creator ct = new Creator();
                IGreet weekDayStatus = ct.FactoryMethod();
                Console.WriteLine(weekDayStatus.Hello());
                Console.ReadLine();

            }
        }
 

Up Next
    Ebook Download
    View all
    Learn
    View all