In the daily development process, often encounter some classes do not need to re-instantiate, such as database connection, in this case, the singleton mode is the best solution. Just the last interview has been asked about this model, today to make a summary.
Let's take a look at one of the simplest implementations of the singleton pattern:
The results of the operation are as follows:
But this is strictly not a true singleton pattern, because the user can simply instantiate new objects by using the newly keyword.
$test 1 = new Singleton (), $test 2 = new Singleton ();
The results of the operation are as follows: So we're going to make a little improvement on our code to set the access level of the construction method to protected:
When the user attempts to instantiate a new object with the newly keyword, the error is reported as follows:
Of course, a cunning user can still clone a new object by using the Clone keyword:
$test 1 = singleton::getinstance (), $test 2 = Clone $test 1;if ($test 1 = = = $test 2) { echo "is the same object";} else{ echo "Not the same object";}
Operation Result:
So we're going to declare the __clone method as protected:
!--? phpclass singleton{static $instance; protected function __construct () {} static function getinstance () {if (Is_null (self:: $instance)) { Self:: $instance = new self (); } return Self:: $instance; } protected function __clone () {}} $test 1 = singleton::getinstance (), $test 2 = Clone $test 1;if ($test 1 = = = $ TEST2) {echo "is the same object";} else{echo "Not the same object";} When a user attempts to clone a new object with the Clone keyword, the error is reported as follows:
Therefore, in order to implement a singleton pattern in strict sense, we should pay attention to the following points:
1, declare the constructor as protected;
2, create a static method of getinstance to get the static variable that holds the class,
3, declare the __clone method as protected
Of course in actual development, In most cases, you can simply implement a simple singleton pattern (the first example is written).
Copyright notice: This article for Bo Master original article, without Bo Master permission not reproduced.