Sunday, August 14, 2011

Singlton Pattern


Singlton Pattern
In software engineering, the singleton pattern is a design pattern that is used to restrict instantiation of a class to one object (an implementation of the mathematical concept of singleton). This is useful when exactly one object is needed to coordinate actions across the system. The concept is sometimes generalized to systems that operate more efficiently when only one object exists, or that restrict the instantiation to a certain number of objects (say, five). Some consider it an anti-pattern, judging that it is overused, introduces unnecessary limitations in situations where a sole instance of a class is not actually required, and introduces global state into an application

Implementation
Implementation of a singleton pattern must satisfy the single instance and global access principles. It requires a mechanism to access the singleton class member without creating a class object and a mechanism to persist the value of class members among class objects. The singleton pattern is implemented by creating a class with a method that creates a new instance of the class if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made protected (not private, because reuse and unit test could need to access the constructor). Note the distinction between a simple static instance of a class and a singleton: although a singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed. Another notable difference is that static member classes cannot implement an interface, unless that interface is simply a marker. So if the class has to realize a contract expressed by an interface, it really has to be a singleton.
The singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a singleton does not yet exist, they both must check for an instance of the singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.
The classic solution to this problem is to use mutual exclusion on the class that indicates that the object is being instantiated


Simple way

This solution is thread-safe without requiring special language constructs, but it may lack the laziness of the one below. The INSTANCE is created as soon as the Singleton class is initialized. That might even be long before getInstance() is called. It might be (for example) when some static method of the class is used. If laziness is not needed or the instance needs to be created early in the application's execution, or your class has no other static members or methods that could prompt early initialization (and thus creation of the instance), this (slightly) simpler solution can be used:
 public class Singleton
{
   private static final Singleton INSTANCE = new Singleton();

   // Private constructor prevents instantiation from other classes
   private Singleton() {}
   public static Singleton getInstance() {
      return INSTANCE;
   }
 }
C#
/// <summary>
/// Thread-safe singleton example created at first call
/// </summary>
public sealed class Singleton
{
    private static Singleton _instance = new Singleton();

    private Singleton() { }

    public static Singleton Instance
    {
        get
        {
           return _instance;
        }
    }
}

Issue with Singleton Pattern

  1. Hides dependencies – A component that uses one or more singletons is hiding crucial information about your dependencies. It doesn’t take long for calls to a singleton to creep through your code base like kudzu, slowly attaching itself to every class in the system. Exposing that dependency forces you to think about it as you use a component. It also makes it more reusable as the caller can understand its requirements and how they might be satisfied.
  2. Hard to test – The hidden coupling of users on a singleton makes testing a nightmare as there is no way to mock out or inject a test instance of the singleton. Also, the state of the singleton affects the execution of a suite of tests such that they are not properly isolated from each other.
  3. Hard to subclass – Since initialization occurs in a singleton in static code, it is not amenable to subclassing because subclasses inherit the initialization code without the chance to override it.
  4. It’s a lie! (in most Java systems) – Singletons in Java are based on static variables, which are held per-classloader, not per-VM. In most systems of any complexity these days (any based on an app server, OSGi, Eclipse, plugins, etc) many classloaders will be involved. In that case, it is quite easy for two plugins to create their own instance of a singleton. Sometimes this is done by design and is desirable. But it’s also easy to screw up. It’s also usually critical that the singleton get created in the right classloader, which can make lazily constructing the singleton tricky.
  5. A singleton today is a multiple tomorrow – It’s not at all unusual to discover that you now need 2 or more of something you previously only needed one of. Hard-coding the singleton pattern into your code makes it impossible to satisfy that demand later. This probably seems really weird if it hasn’t happened to you, but it has happened more than once to me.

When to use
There are still some cases where singletons are a valid choice.
One is logging. Logging is so pervasive that unless you use some fairly heavy-handed dependency injection or AOP, it is not feasible to inject every class in the system with a logger. Instead, this is a case where using static methods or singletons are probably worth the compromise.
Another common use is to obtain a handle to a service locator (think JNDI) that knows how to access everything else. This is actually one way to change your entire system from using many singletons to using one singleton that knows how to find the others. This is a valid technique that addresses some of the inherent problems (mockability, testing) with singletons and may be a less invasive change to a legacy code base.
Swing or other client-side UIs are another case where singletons may be a valid choice. In the case of a Java desktop app, it is likely that you have more complete control over your deployment environment than you do in a server-side application. In this case, it can be acceptable to have a manager class managing some state as a singleton in the VM. However, my preference would be to go the extra step to expose that dependency.