| by Dhananjay Yadav | 4 comments

What is Singleton Design Pattern?

Singleton pattern is a technique to provide a class global state. Once we have created the instance of the class we can use the existing instance multiple times. So it restricts the multiple instantiation of a class.It is a great example of re-usability in Object Oriented Programming System.

How it works?
We restrict the constructor while declaring it as private , of the class to access it from outside and a static method is created that returns the instance.

Example in PHP:

1
<?php 
class SingletonClass {
  private static $the_instance = null;
  
  //the private constructor
  private function __construct()
  {
    
  }
 
 //public static function to return the instance
  public static function getInstance()
  {
    if (self::$the_instance == null)
    {
      self::$the_instance = new SingletonClass();
    }
 
    return self::$the_instance;
  }
}
?>

Usage of Singleton Class:

Connecting A database and use exiting connection, to avoid multiple open connection issue:

<?php 
	class DB {

	  private static $instance = null;
	  private $conn;
	  
	  private $host = 'localhost';
	  private $user = 'root';
	  private $pass = 'password';
	  private $name = 'my_database_name';
	   
	  private function __construct()
	  {
	    $this->conn = new PDO("mysql:host={$this->host};
	    dbname={$this->name}", $this->user,$this->pass,
	    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));
	  }
	  
	  public static function getInstance()
	  {
	    if(!self::$instance)
	    {
	      self::$instance = new DB();
	    }
	   
	    return self::$instance;
	  }
	  
	  public function dbConnection()
	  {
	    return $this->conn;
	  }
	} 
?>

Now creating an Instance using the static method:


<?php 
	$the_instance = DB::getInstance();
	$conn = $the_instance->getConnection();
?>

Dhananjay Yadav

Dhananjay Yadav

A Computer Science graduate, a blogger, a web developer worked on various web technologies.

Other Post by :