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:
Post a Comment