Aleks Grinberg

February 11, 2010

Singleton

Filed under: Design Patterns — aleksgrinberg @ 2:26 am

Singleton is a class that can be instantiated only once to coordinate actions across the system. Below is the simpe implementation of the Singleton class.

 class Singleton
    {
        private static Singleton instance;

        // Note: the constructor is protected
        protected Singleton()
        {
        }

        public static Singleton GetInstance()
        {
            //lazy initialization
            if (instance == null)
            {
                instance = new Singleton();
            }

            return instance;
        }
    }
}

Let’s make multiple calls of the Singleton class and make sure they share the same instance of this class. We can not use the new() keyword since the constructor is protected:

static void Main()
{
     Singleton instance1 = Singleton.GetInstance();
     Singleton instance2 = Singleton.GetInstance();
     if ( instance1 == instance2 )
     {
         Console.WriteLine("As you may see - I'm the Singleton!");
     }
     Console.Read();
}

As we may expect the execution of this code will return a confirmation from the Singleton class.  The Singleton class requires small modification for making it useable in the multithreading system:

 class Singleton
 {
        private static Singleton instance;
        private static object syncLock = new Object();

        protected Singleton()
        {
        }

        public static Singleton GetInstance()
        {
            lock(syncLock)
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
                return instance;
            }

            return instance;
        }
    }
}

Apparently the Singleton class may include more methods and instance variables to be shared across the system.

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.