If a design requires only one instance of a particular class throughout an execution is known as singleton design pattern.
It ensures single instance of a class for the entire request life-cycle in a web application. Lets check the following code snippet of a basic singleton example in PHP:
It ensures single instance of a class for the entire request life-cycle in a web application. Lets check the following code snippet of a basic singleton example in PHP:
class Logging
{
private static $instance;
private function __construct() {
}
public static function getInstance(){
if(!isset(self::$instance)){
self::$instance = new Logging();
}
return self::$instance;
}
}
$firstObj = Logging::getInstance();
$secondObj = Logging::getInstance();
if($firstObj === $secondObj) {
echo 'Both objects are same';
}
else{
echo 'Both objects are not same';
}
Output
Both objects are same
Where singleton pattern should be used?
In following situations we can use singleton pattern:- In database configuration and connection singleton pattern can be used to keep single connection throughout the life-cycle
- For designing the logger class we can consider singleton design patter
Comments
Post a Comment