Application analysis of singleton pattern based on php design pattern

  • 2020-06-03 05:56:26
  • OfStack

Singleton pattern: Simply put, an object is only responsible for a particular task.

Singleton class:
1. The constructor needs to be marked as private. The singleton class cannot be instantiated in other classes, but can only be instantiated by itself
2. Have an instance static member variable that holds the class
3. Have a public static method that accesses this instance. [Common getInstance() methods are used to instantiate singleton classes, which can be detected by the instanceof operator.]
Note: The method with EACH ___ 10en () needs to be created to prevent objects from being copied
Function:
1. The application of php is mainly used for database, so there will be a large number of database operations in one application. The use of singleton mode can avoid a large number of resources consumed by new operations
2. If a class is required to control some configuration information globally, singleton mode can be easily implemented. See section FrontController of ZF
3. Request summary in 1 page, easy to debug, because all the code is concentrated in 1 class, we can set hooks in the class, output log, so as to avoid var_dump, echo everywhere.


<?php 
class DanLi{ 
    // Static member variable  
    private static $_instance; 
    // A private constructor  
    private function __construct(){ 
    } 
    // Prevents objects from being cloned  
    public function __clone(){ 
        trigger_error('Clone is not allow!',E_USER_ERROR); 
    } 
    public static function getInstance(){ 
        if(!(self::$_instance instanceof self)){ 
            self::$_instance = new self; 
        } 
        return self::$_instance; 
    } 
    public function test(){ 
        echo "ok"; 
    } 
} 

// Error: $danli = new DanLi(); $danli_clone = clone $danli; 
// Correct: $danli = DanLi::getInstance(); $danli->test(); 

?>


Related articles: