This article mainly introduces the Singleton mode in the php design mode, and uses php to implement Singleton mode. if you are interested, you can refer to it to ensure that one class has only one instance, and provides a global access point to access it.
The Singleton mode has three features:
1. a class has only one instance.
2. it must create the instance on its own.
3. you must provide this instance to the entire system.
I. Structure of Singleton mode
II. main roles in Singleton mode
Singleton defines an Instance operation that allows the customer to access its unique Instance. Instance is a class method. Creates a unique instance.
III. Advantages of Singleton mode
1. controlled access to a unique instance
2. narrowing down the namespace Singleton mode is an improvement for global variables. It avoids the global variables that store unique instances from polluting the namespace.
3. a subclass can be added to the list class of operations and representations. In addition, it is easy to configure an application using this extension class instance. You can use the instance of the class you need to configure the application at runtime.
4. allow variable target instances (multi-sample mode)
5. more flexible than class operations
IV. applicable scenarios of Singleton mode
1. when the class can only have one instance and the customer can access it from a well-known access point
2. this unique instance should be extensible through subclass. And the user should be able to use an extended instance without changing the code.
V. Singleton mode and other modes]
Factory method mode: The Singleton mode uses factory mode to provide its own instances.
Abstract factory mode: the abstract factory mode can use the Singleton mode to design a factory class into a singleton class.
Builder mode: you can design a specific build class into a singleton mode.
V. example of single-instance PHP
<? Php/*** lazy Singleton class */class Singleton {/*** static finished variable save global instance */private static $ _ instance = NULL; /*** default constructor of privatization to ensure that the external world cannot directly instantiate */private function _ construct () {}/*** static factory method, return the unique instance */public static function getInstance () {if (is_null (self ::$ _ instance) {self ::$ _ instance = new Singleton ();} return self: $ _ instance;}/*** prevents the user from cloning an instance */public function _ clone () {die ('Clone is not allowed. '. e_US ER_ERROR);}/*** test method */public function Test () {echo 'Singleton test! ';}}/*** Client */class Client {/*** Main program. */public static function main () {$ instance = Singleton: getInstance (); $ instance-> test () ;}} Client: main ();?>
The above is the code that uses php to implement the Singleton mode. There are also some concepts about Singleton mode, which will be helpful for your learning.