


Application Analysis of Single Case and Multiple Case Design Patterns in PHP_PHP Tutorial
Jul 21, 2016 pm 03:01 PM
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:
<?php
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:
<?php
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);
}
};
?>

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian

How To Set Up Visual Studio Code (VS Code) for PHP Development
