Before you learn this singleton mode, please choose to read another design mode
PHP design mode-Simple Factory mode (static Factory method mode)
PHP design mode-factory method mode (polymorphism Factory mode) (virtual construction sub-mode)
PHP design mode-Abstract Factory mode
As an object's creation mode, Singleton mode ensures that a class has only one instance, and instantiates it itself and provides it to the entire system, a class called a singleton class
The singleton mode (singleton) has three features
1. Only one instance of a class
2. It must create this instance on its own
3. It must provide this instance to the entire system on its own
Legend:
code example:
Singleton mode is divided into lazy singleton patterns in Java | a hungry man single-case mode
However, the A hungry man singleton mode is not available in PHP, and I will list the code below, which will prompt the error at run-time. Here is just a concept of usage.
A hungry man single-case mode:
1 //This is the A Hungry man single-case pattern .2 //But in PHP, this is not allowed to be practical. So we're basically talking about PHP's lazy singleton pattern.3 classTest {4 Private Static $_instance=NewSelf ();5 6 Public Static functiongetinstance () {7 returnSelf::$_instance;8 }9 Ten Private function__construct () { One //Check instantiation A Echo"Instance\n"; - } - the } - $a= Test::getinstance (); - Var_dump($a);
Lazy single-case mode:
1 //Lazy Single-case mode2 3 classTest {4 Private Static $_instance;5 6 Public Static functiongetinstance () {7 if(!self::$_instance){8Self::$_instance=NewSelf ();9 }Ten returnSelf::$_instance; One } A - Private function__construct () { - //Check instantiation the Echo"Instance\n"; - } - - } + - $a= Test::getinstance (); + Var_dump($a);
PHP design mode-singleton mode (singleton)