Tuesday, February 28, 2012

Design Patterns: Singleton


       During software development, you may need to create one and only one instance of a certain class when the application is running. For example, the database connection object. And you want the class maintain this rule by itself. This class is called a "Singleton" class. Let's look at a simple example:

       We need to make a class named SystemSettings a singleton class, we define it as following:

       public class SystemSettings
    {
        private static int instanceNum = 0;
        private static SystemSettings settings;

        private SystemSettings() { instanceNum++; }

        public static SystemSettings getInstance()
        {
            if (settings == null)
            {
                settings = new SystemSettings();
            }

            return settings;
        }

        public static int InstanceNumber
        {
            get
            {
                return instanceNum;
            }
        }
    }

       The private constructor make sure other the SystemSettings class instance can not be created from outside . getInstance() method make sure there is only one instance of settings class is created. We can write a unit test to test if this singleton class works like it should:

       [TestMethod]
     public void SingletonTest()
     {
           SystemSettings settings = SystemSettings.getInstance();
            Assert.IsTrue(SystemSettings.InstanceNumber == 1);

            settings = SystemSettings.getInstance();

            Assert.IsTrue(SystemSettings.InstanceNumber == 1);
      }

       As we expect, the test is successful.

No comments: