Singleton

From CDOT Wiki
Revision as of 18:28, 8 March 2007 by Yshen6 (talk | contribs)
Jump to: navigation, search

Go Back Pattern List

Introduction

Singleton pattern Ensure a class only has one instance, and provide a global point of access to it. This is useful when exactly one object is needed to coordinate actions across the system.

Implementation

  • Singleton pattern is implemented by creating a class with a method that creates a new instance of the object 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 either private or protected.

UML Diagram

Singleton UML.png

Sample Code

Singleton pattern in C#:

class Singleton
{
  private static Singleton instance;

  // Note: Constructor is 'protected' 
  protected Singleton() 
  {
  }

  public static Singleton Instance()
  {
    // Use 'Lazy initialization' 
    if (instance == null)
    {
      instance = new Singleton();
    }

    return instance;
  }
}

Singleton pattern in PHP 5:

<?php
class Singleton {
  // object instance
  static $instance;
  
  private function __construct() {}
  private function __clone() {}
  
  public static function getInstance() {
    if (!Singleton::$instance instanceof self) {
      Singleton::$instance = new self();
    }
    return Singleton::$instance;
  }
}
?>

References

http://en.wikipedia.org/wiki/Singleton_pattern