Static Class and the need of Singleton Pattern

Wikipedia says:  
"Singleton pattern is a design pattern which restricts the instantiation of a class to one object"
Doesn't a static class do the same for us??.. Confusing??. Yes it is..so lets spend some time and understand the need of Singleton pattern.

When a Static Class can be used?

  • If you are thinking of exposing few utility operation or constant values for the entire application: Since static class doesn't need instantiation, any utility operations can be used across the application without creating objects of the utility class. This very concept gives use many benefits:
  1. Functions and properties can be used simply with the class name.
  2. Since the utility functions/constants will remain the same no matter how many instances of the holding class is made, it's wise to have only once instance of the class. This reduces the memory related concerns alot.
  • Extension MethodsWe can enhance the functional capability of an existing class without actually modifying it, by using the concept of extension methods. See the link http://msdn.microsoft.com/en-us/library/vstudio/bb383974.aspx. In this link, the enumeration class is being extended to have a method "Passing()", which otherwise doesn't exist in the class implementation. 
When to avoid a Static Class?
  • When holding data: We should avoid static class in scenarios where we are holding data which is frequently manipulated in the application. As an exception we can hold constant values.
Where all static classes fail to serve us?
  • Non deterministic initialization: The static class holds a single memory location in the application cycle and how, when and where of it is controlled by the CLR. Usually the whole process is very in-deterministic in nature. If we want to  assure certain operations before we actually start using the static class, then we fail to do so.
  • They can't be extended using inheritance: We might want to override the utility methods in to change behavior as per the requirement, but we can't do it with a static class.
  • They can't be loaded on demand and deposed there after: If we are holding huge data in a static class, then we cannot load it as and when needed and dispose it when not required.
  • They can't extend any other class or interface
From the above discussion we got a fair idea of the boundaries of a Static class. At most of the places where a Static class fails, a Singleton pattern turns out to be a life saver. 
In my next blog I will try diving deep into the Singleton pattern and will find out the practical benefits we can reap out of it.

Comments

Popular Posts