Singleton Design Pattern C#

Ensure a class only has one instance, and provide a global point of access to it.

namespace TestSingleton
{
    class Program
    {
        static void Main(string[] args)
        {
            Logger logger1 = Logger.GetInstance();
            Logger logger2 = Logger.GetInstance();

            logger1.WriteMessage("This is a message from logger1");
            logger2.WriteMessage("This is a message from logger2");

            //This verifies that there is only one instance was created.
            if (logger1 == logger2)
            {
                Console.WriteLine("Both objects are of the same instance");
            }

            Console.ReadKey();
        }
    }

    /// <summary>
    /// Singleton Class
    /// </summary>
    public sealed class Logger
    {
        //Private Constructor
        private Logger() { }

        //Private instance variable
        private static Logger _loggerInstance = null;

        private static readonly object _threadsafeLock = new object();

        //Method to get instance (With Multithreaded thread safety and Lazy Instantiation)
        public static Logger GetInstance()
        {
            if (_loggerInstance == null)
            {
                lock (_threadsafeLock)
                {
                    _loggerInstance = _loggerInstance ?? new Logger();
                }
            }

            return _loggerInstance;
        }

        /// <summary>
        /// Write message to console or text file based on the requirement.
        /// </summary>
        public void WriteMessage(string message)
        {
            Console.WriteLine(message);
        }
    }
}

Ouptut:
This is a message from logger1
This is a message from logger2
Both objects are of the same instance

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s