Introduction to the Singleton Definition Pattern

No.of Views677
Bookmarked0 times
Downloads 
Votes0
By  Chinna Srihari   On  21 Oct 2010 11:10:58
Tag : Design Patterns , General
This is a quite simple design pattern, let me tell you one thing there are many design patterns that they are implicitly singletons. I rather recommend to understanding this one first before going through other patterns.
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

What is Singleton Definition Pattern?
 
This is a quite simple design pattern, let me tell you one thing there are many design patterns that they are implicitly singletons. I rather recommend to understanding this one first before going through other patterns.
 
There are many cases that we need only one instance of the object through-out the application, may be specific scope like user specific and the class should not allow the users or other classes creating object on their own. Apart from one instance, the same object should provide or control the creation of object and provide the instance to anyone who requires that object.
 
Standard definition is that: ‘Ensure a class has only one instance, and provide a global point of access to it.
 
Design
 
In the definition, the first part is ‘Ensure a class has only one instance’. How can we say that there is only one instance?
 
If and only if the same class is not creating himself and controlling the access to it we can’t ensure that there is only one instance. So how to avoid issuing ‘New’ key word on the object? Make the class default constructor as private. That’s it no one will be able to issue ‘new’ key word on your class.
public class MySingleton
          {
                    private MySingleton (){}
 }
 
 
 Now who will create the instance of the class, declare a private variable of class type and initialize it at class scope.
public class MySingleton
         {
                    private MySingleton _mySingleton = new MySingleton ();
 
                    private MySingleton ()
                   {
                   }
}
 
Now the question here is that until unless the constructor is called this class scope variable will not the initialized, so what to do now? Somebody somehow something should be called in the class so that which will initialize or create the instance by calling the constructor. So we have to take the help of static method or property so that without initializing the class we can make call on it and in turn it will create a object and return for use. Make the private class scope variable as static, you know why right? If it is not static we can’t call in side static method of property.
public class MySingleton
        {
                 private static MySingleton _mySingleton = new MySingleton ();
 
 private MySingleton (){}
 
                public static MySingleton GetInstance ()
                {
                                return _mySingleton;
                }
          }
 
Now what happens is, when we call static method, which is the private variable will initialize, when it is, the ‘new’ key word will call the private constructor that’s it. We have class object created.
As Instance method is Static which can’t be overtraded in the derived calls, as Static methods are not virtual.
Now there is problem here what if, if two threads trying to create the instance? There are many way to implement this. One of it is here. Also remember if the variable is not fully initialized it should not be accessed. Here is the complete example
public sealed class MySingleton
        //volatile ensures that variable is fully initilized before accessing it.
        private static volatile MySingleton _instance;
        private static object lockObject = new object();
 
        //private construct to avoid Newing the class
        private MySingleton() { }
 
        //double checking for multi threading
        public static MySingleton Insatnce()
        {
            if (_instance ==null)
            {
                //Allows only one thread to initialise the object
                lock(lockObject)
                {
                    if (_instance==null)
                        _instance = new MySingleton();
               }
            }
            return _instance;
        }
Now you will say it is like a static class what the difference is? Basic difference is that in multithread environment maintains one instance per thread where as Singleton is one across threads.
 
 Another way of implementing the same pattern
public class Singleton
    {
        // A static member to hold a reference to the singleton instance.
        private static Singleton instance;
 
// A static constructor to create the singleton instance. Another alternative is to use lazy initialization in the Instance property.
        static Singleton()
        {
            instance = new Singleton();
        }
// A private constructor to stop code from creating additional instances of the singleton type.
        private Singleton() { }
 
        // A public property to provide access to the singleton instance.
        public static Singleton Instance
        {
            get { return instance; }
        }
}
 
Let us see the Real Example
 
ü Requirement
 
In one of my applications; we had requirement like showing address in two different formats. One format is like countries those have States will use one format and those countries that didn’t have States use other format. But client didn’t have data for all countries. If the states are available in the data bases then we need to show the State drop down or else don’t Show and it is dynamic. Here the usage for state are high, States are accessed frequently based on the country code (Universal code).
 
ü Design Approach
·         States are accessed frequently.
·         Not sure when the states data will be available.
·         Same information across the application has to be used by all the users.
·         Decided to use the Singleton with Parameterized by country code
·         Here instances are maintained same across the application based on the country code rather than the same instance.
 
ü Code
    public sealed class StateSingleton
    {
      public string _countryCode;
      public ArrayList _states;
private static object _object = new object();
private static volatile HashSet<StateSingleton> _stateSingletonList = new HashSet<StateSingleton>();
      private StateSingleton(){}
      public static StateSingleton GetInstance(string countryCode)
      {
          StateSingleton instance = new StateSingleton();
          if (!isExists(countryCode))
          {
              if (instance != null)
              {
                  lock (_object)
                  {
                      if (instance != null)
                      {
                          instance._countryCode = countryCode;
                          instance._states = getStates();
                          _stateSingletonList.Add(instance);
                      }
                  }
              }
          }
         else
          {
            lock (_object)
                  {
instance = _stateSingletonList.Where<StateSingleton>(a => a._countryCode == countryCode).Single();
}
          }
          return instance;
      }
      private static bool isExists(string countryCode)
      {
if (_stateSingletonList.Where<StateSingleton>(stateSingleton => stateSingleton._countryCode == countryCode).Count() > 0)
           {
              return true;
           }
           else
           {
              return false;
           }
      }
      private static ArrayList getStates()
      {
          return new ArrayList {"a","b"};
      }
}

Hope this helps

Thanks,

Chinna

 
Sign Up to vote for this article
 
About Author
 
Chinna Srihari
Occupation-Software Engineer
Company-
Member Type-Junior
Location-India
Joined date-17 Jun 2010
Home Page-
Blog Page-
Having 12 + years of IT experience, 2.5 years as Technical Management experience and 1.5 year of onsite coordinator experience and rest 8+ years of technical activities including Project Leader, Tech Lead, Designer, PQL, and Developer experience in Quality Management System (CMM-level 5, SEI-CMM-level 5).
 
 
Other popularSectionarticles
    Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
    Published Date : 23/Oct/2010
    As a developer we might have noticed that creation of some class is very difficult and number of time that we need to create. Such object creation every time is very expensive in terms of system resources. If we can cache that kind of object show how will surely boost the application performance and resource usage can be saved. This where object pool design pattern will help development community to cache the objects. Some time it is also called as Object cache or Resource cache design pattern.
    Published Date : 21/Oct/2010
    The Command pattern creates distance between the client that requests an operation and the object that can perform it.
    Published Date : 20/Sep/2010
    Provide a unified interface to a set of interfaces in a subsystem. Façade defines a higher-level interface that makes the subsystem easier to use.
    Published Date : 22/Oct/2010
    A fully initialized instance to be copied or cloned. The Prototype pattern specifies the kind of objects to create using a prototypical instance.
    Published Date : 22/Oct/2010
Comments
There is no comments for this articles.
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top