Friday, January 29, 2010

Design patterns : Singleton pattern

Singleton design pattern is required when you want to allow only one instance of the class to be created. Database connections and filesystems are examples where singleton classes might be required. You can also use a singleton class to store variables which need global access - thereby limiting the scope of those variables and keeping the global space variable free.

With singleton design pattern, following points need to be ensured
  • Ensure that only a single instance of the class is created.
  • Provide a global point of access to the object.
  • The creation of the object should be thread safe to avoid multiple instances in a multi-threaded environment.

An illustration in java (from wikipedia)

public class Singleton 
{
  // Private constructor prevents instantiation from other classes
  private Singleton() {}
         
  /**
   * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
   * or the first access to SingletonHolder.INSTANCE, not before.
  */
  private static class SingletonHolder 
  { 
    private static final Singleton INSTANCE = new Singleton();
  }
                                      
  public static Singleton getInstance() 
  {
    return SingletonHolder.INSTANCE;
  }
}

Another illustration in php

class singleton
{
  private static $_instance;
  
  //private constructor to prevent instantiation from other classes
  private function __construct()
  {  }

  private function __destruct()
  {  }

  // only first call to getInstance creates and returns an instance. 
  // next call returns the already created instance.
  public static function getInstance()
  {
    if(self::$_instance === null)
    {
      self::$_instance = new self();
    }
    return self::$_instance;
  }

}

No comments: