PHP single-state design mode
Title: single-state design mode, single-case design mode, and single-piece design mode (don't be asked during the interview)
Concept:Singleton (Singleton) mode is mainly used to ensure that only one Class exists in an object-oriented programming language.
Purpose:In many operations, such as creating a directory database connection, such single-threaded operations are required.
Implementation method:
(1) If you want a class to have only one object, you must first prevent the class from creating objects and be cloned (_ clone ), therefore, we need to privatize the constructor and clone methods.
(2) provide a static method in the class to create an object
(3) provide a static attribute in the class to store the instantiated object (if the object exists, it will not be instantiated, so as to ensure that the object is instantiated only once)
Example:
Class Instance {// static variable save global instance private static $ _ Instance = null; // private constructor to prevent external instantiation object private function _ construct () {echo 'when I see it several times, it indicates how many times I have been created';} // private clone function to prevent external clone object private function _ clone () {} // static method. in Singleton mode, the access entry static public function getInstance () {if (is_null (self ::$ _ instance) {self :: $ _ instance = new self ();} return self: $ _ instance;} Instance: getInstance (); Instance :: getInstance ();