Thursday, November 15, 2012

Static Classes & Singleton

Singleton is the most widely known Design Pattern. Singleton makes sure that one only one instance of a class is created and the same instance is used by other programs and classes.An implementation of a Singleton class is shown below:


class Program
{
    static void Main(string[] args)
    {
            SingletonDemo s = SingletonDemo.GetInstance();
            s.M1();
            Console.Read();
        }
}
   
    public class SingletonDemo
    {
        //Single Instance
        private static SingletonDemo instance = new SingletonDemo();
        //Private Constructor
        private SingletonDemo() { }
        //Method to get the single instance

        public static SingletonDemo GetInstance()
        {
            return instance;
        }

        public void M1()
        {
            Console.WriteLine("SingletonDemo::M1 called");
        }
    }

This is just like any normal class, we are just preventing the creation of multiple instances by making the constructor private and the GetInstance method makes sure that the same instance is returned in all the calls to it.


Now the question is Why Can’t We Make Them Static Classes?
Let change this code to make it a static class.


class Program
{
    static void Main(string[] args)
    {
        StaticDemo.M1();
        Console.Read();
    }
}

public static class StaticDemo
{
    public static void M1()
    {
        Console.WriteLine("StaticDemo::M1 called");
    }
}
This looks all very simple. But there are some restrictions and limitations of the static classes.

Static classes cannot be instantiated.Static classes cannot have instance constructors.
Static classes can only have static constructors
Static classes are sealed. You cannot derive from a static class.
Static classes cannot derive from any other classes other than System.Object
Static classes cannot implement interfaces.
Static classes can only have static members

So from the above list of don’t haves its quite clear that static classes lack certain basic OO features like inheritance & polymorphic behavior. Static classes are containers to logically group a set of members.


The Singleton pattern has several advantages over static classes. First, a singleton can extend classes and implement interfaces, while a static class cannot.

Singleton can implement interfaces, inherit from other classes and allow inheritance.


Singleton object stores in Heap but, static object stores in stack
We can clone the object of Singleton but, we can not clone the static class object
Singleton class follow the OOP(object oriented principles) but not static class
we can implement interface with Singleton class but not with Static class.


Another advantage of a singleton is that it can easily be serialized, which may be necessary if you need to save its state to disc, or send it somewhere remotely.

No comments:

Post a Comment