This article is the PHP design pattern in a single case and a number of design patterns in the application of a detailed analysis of the introduction, the need for friends to refer to the
The single example (Singleton) pattern and the Uncommon Multiple (Multiton) pattern control the number of classes in the application. such as the pattern name, a singleton can only be instantiated once, with only one object, and multiple instances can be instantiated multiple times.
Based on Singleton features, we often use singleton to configure the application and define variables that may be accessed at any time in the application. However, it is sometimes not recommended to use singleton because it generates a global state and
The single Root object does not encapsulate any system functionality. In most cases, unit testing and debugging can become difficult. The reader decides according to the situation.
code Example:
Copy Code code as follows:
<?php
class singletonexample{
Private Function __construct () {}//prevents direct instantiation
public static function getinstance () {//not associated with any object
static $instance =null; All code that calls this function shares the variable without having to be a static variable for the class
if ($instance ==null) {
$instance =new singletonexample ();
}
return $instance;
}
}
$obj 1=singletonexample::getinstance ();
$obj 2=singletonexample::getinstance ();
var_dump ($obj 1=== $obj 2);/True is the same instance
?>
Multiton is similar to singleton, which requires the getinstance () function to pass key values.
Only a unique object instance exists for a given key value. If there are multiple nodes, each node has a unique table identifier, and each node in a single execution (such as the node in the CMS) may occur several times, then you can use the Multiton mode to implement these nodes Ah, Multiton save memory, and ensure that multiple instances of the same object do not collide.
Example:
Copy Code code as follows:
<?php
Class multitonexample{
Private Function __construct () {}//prevents direct instantiation
public static function getinstance ($key) {
Static $instance =array ();
if (!array_key_exists ($key, $instance)) {
$instance [$key]=new singletonexample ();
}
Return $instance ($key);
}
};
?>