The Singleton pattern and the less common Multiton pattern control the number of classes in an application. As in the pattern name, the singleton can only be instantiated once and has only one object, while the multi-instance pattern can be instantiated multiple times.
Based on the characteristics of Singleton, we often use Singleton to configure applications and define variables that may be accessed at any time in the application. But sometimes Singleton is not recommended because it generates a global state and
This single root object does not encapsulate any system functionality. In many cases, this makes unit testing and debugging difficult. Readers make their own decisions based on circumstances.
Code example:
Copy code The code is as follows:
class SingletonExample{
private function __construct(){}//Prevent direct instantiation
public static function getInstance(){ //Not associated with any object
static $instance=null; //Call All codes of this function share this variable, there is no need to make it a static variable of the class
if($instance==null){
$instance=new SingletonExample();
}
return $ instance;
}
}
$obj1=SingletonExample::getInstance();
$obj2=SingletonExample::getInstance();
var_dump($obj1===$obj2); // true is the same instance
?>
Multiton is similar to singleton, except that the latter requires the getInstance() function to pass the key value.
There will only be a unique object instance for a given key value. If there are multiple nodes, each node has a unique identifier, and each node may appear in a single execution (such as nodes in cms) Multiple times, then you can use Multiton mode to implement these nodes. Multiton saves memory and ensures that multiple instances of the same object do not conflict.
Example:
Copy code The code is as follows:
class MultitonExample{
private function __construct(){}//Prevent direct instantiation
public static function getInstance($key){
static $instance=array();
if(!array_key_exists($key,$instance)){
$instance[$key ]=new SingletonExample();
}
return $instance($key);
}
};
?>
http://www.bkjia.com/PHPjc/327983.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/327983.htmlTechArticleThe Singleton pattern and the uncommon Multiton pattern control the number of classes in the application . Such as the pattern name, a singleton can only be instantiated once, there is only one object, the multiple instance pattern can...