Home > Development > Double Checking Singleton Design Pattern

Double Checking Singleton Design Pattern

September 17, 2010 Leave a comment Go to comments

Hi all,
I have some source code on how to create a singleton that is thread safe in C#.

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

UML
UML

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

namespace LazyEvaluation
{

    public class ConfigurationA
    {
        private string servername;

        public string Servername
        {
            get { return servername; }
            set { servername = value; }
        }

        private string serverport;

        public string Serverport
        {
            get { return serverport; }
            set { serverport = value; }
        }

        private string username;

        public string Username
        {
            get { return username; }
            set { username = value; }
        }

        private string password;

        public string Password
        {
            get { return password; }
            set { password = value; }
        }

        private static ConfigurationA configuration;
        private static object locker = new object();

        private ConfigurationA(){}

        public static ConfigurationA Instance
        {
            get
            {
                if (configuration != null)
                {
                    return configuration;
                }

                lock (locker)
                {
                    if (configuration == null)
                    {
                        configuration = new ConfigurationA();
                    }
                    return configuration;
                }
            }
        }

    }

    class Program
    {
        static void Main(string[] args)
        {

            ConfigurationA c1 = ConfigurationA.Instance;
            ConfigurationA c2 = ConfigurationA.Instance;

            Console.WriteLine("Same instance: {0}", ReferenceEquals(c1, c2));

            Console.WriteLine("Press any key to exit..");
            Console.ReadKey();
        }
    }
}

Blair…

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: