Singleton and Static Classes

In this blog we will discuss the Singleton & Static Classes, their pro and cons. On a higher level they both have approximately same functionality ans usages. As you know both Singleton and Static classes provide a central point of access i.e. there’s only one instance and one way to access it. I have another post which give a lot of insight into Singleton design pattern/ class. So I will not go in-depth into Singleton class implementation here, but will give some introduction which will be helpful for comparison with Static classes.

Singleton

When it is used
o    Used when we want only one object is shared between clients.
o    Client should not create any object.
o    The object should be created only once and then the same object should service all the client requests.
How to Implement
There are various ways of implementing the singleton pattern in C# based on thread safty, lazy-initialisation and performance.  But all these implementations share four common characteristics:
  • A single constructor, which is private and parameter less. This prevents other classes from instantiating it. 
  • The class is sealed, though this is option or unnecessary, but may help the JIT to optimize things more.
  • A static variable which holds a reference to the single created instance.
  • A public static means of getting the reference to the single created instance, creating one if necessary.
public sealed class SingletonImplementation
{
        //static variable which holds the single instance at any given time
        privatestatic SingletonImplementationtheInstance;
        //constructor is private so we cannot create instance of the class directly
        privateSingletonImplementation()
        {
        }
        //static method used to create and return the instance of the class
        public static SingletonImplementationGetInstance()
        {
            lock(typeof(SingletonImplementation))
            {
                if(theInstance == null)
                {
                    theInstance = new SingletonImplementation();
                }
                returntheInstance;
            }
        }
        public int Addition(int i, int j)
        {
            returni+j;
        }
}
//the sample client call will be as follows
public class ClientClass
{
     //calling the singleton class method
     int x = SingletonImplementation.GetInstance().Addition(5,6);
}

Static Class


Is used when we want to share the same instance of the class and its data across the different clients. A sample implementation can be as follows:
public static class StaticClassImplementation
{
        staticStaticClassImplementation()
        {
            // Initialize all of our static members.           
        }
        public static int Addition(int i, int j)
        {
            returni+j;
        }
}
//the sample client call will be as follows
public class ClientClass
{
        //calling the Static class method
         int x = StaticClassImplementation.Addition(5,6);
}

Difference between the two

  • There is no functional difference between the following
        //calling the Static class method
        int x = StaticClassImplementation.Addition(5,6);

       
//calling the singleton class method
        int x = SingletonImplementation.GetInstance().Addition(5,6);
  • Singleton means “single object across the application life cycle”. The scope of singleton is at application level.
  • Static means “We cannot have any object pointer”. The scope of static is at App Domain level.
  • The benefit of Singleton class is it is much more flexible than static classes. Your code will be more flexible if you use a singleton. The code that uses the singleton doesn’t need to know if it is a singleton or a transient object. On the other hand if we are using a static class means we have to call static methods explicitly.
  • Dependency Injection is one of the primary requirements while designing decoupled applications. Static classes once defined could not accommodate any future design changes as by design static classes are rigid and cannot be extended. Singleton on the other hand provides flexibility and also provides sort of a mechanism to control object creation based on various requirements. They can be extended as well if need arises. In other words you are not always tied to a particular implementation.  With Singleton you have the flexibility to make changes as when situation demands.
  • Singleton Class can have value when Class object instantiated between server and client, such a way if three client want to have a shared data between them Singleton can be used. Static are always just shared and have no instance but multiple references.
  • Singleton, as a non-static class, can still implement an interface, supports inheritance, etc. For example, you can’t inherit a static class and override a virtual method in it.
  • Consider that today the application has a global shared object and tomorrow we decide that there has to be more than one instance of it. If you use a singleton, all you need to do is make your constructor public. But if you decide to use a static class, the change would have to be much more intrusive.
  • If we ever decide to add unit tests to your code, replacing a singleton instance with a fake one is much easier (change in one place) compared to having to deal with a whole bunch of static functions that all share global data.
  • If it is a Web application, Static Classes can create some major problems in a concurrent environment (because of shared data), specially when you are also using static variables and static methods.
  • Singleton class does maintains state while Static doesn’t.
  • We can pass Singleton object as parameter.
Here’s a simple rule for usage
  • If design calls for inheritance and variation then we must use a Singleton and not a Static class as we cannot use inheritance with static classes, by definition. In most usages, we would want our Singleton to implement an interface, something you cannot do with a static class.
  • When we want to increase your performance we will encounter situations where we will have to use threading, so when making our application thread-safe we avoid some race situation.
  • Static and Singleton classes will share there values for the entire instance of your application. When we access that object from multiple threads we can reuse or overwrite variables that’s also being used by another object. This will result in some very strange output and it’s hard sometimes to find what is going on since it ain’t easy to simulate this in test cases. We can implement a lock in your methods to introduce thread safety in these classes.

Leave a Comment