Tuesday, September 15, 2015

Real Time Example of Singleton Design Pattern

What is Singleton Design Pattern:

Singleton pattern ensures that a class has only one instance and provides a global access to it.


Code Implemented using C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SingletonSample
{
    class Program
    {
        static void Main(string[] args)
        {
            Singleton obj1 = Singleton.Instance();
            Singleton obj2 = Singleton.Instance();
            Singleton obj3 = Singleton.Instance();
            Singleton obj4 = Singleton.Instance();

            if (obj1 == obj2 && obj2 == obj3 && obj3 == obj4)
            {
                Console.WriteLine("Objects are the same instance");
            }

            // Wait for user
            Console.ReadKey();
        }
    }

    class Singleton
    {
        private static Singleton _instance;

        protected Singleton()
        {

        }

        public static Singleton Instance()
        {
            if (_instance == null)
            {
                _instance = new Singleton();
            }
            return _instance;
        }
    }
}

No comments:

Post a Comment