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:
<?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(); ?>
- 8Shares
Hi, Sir good content.
thanks
Its containing good content please provide me the same for Android Also bro…..!!
Thanks or your feedback,sure will provide same for the amdroid