Summary
Guarantees that a class has only one instance and provides a global access point "GOF95" that accesses it
Characteristics
1, a class has only one instance
2. It must create this instance on its own
3. This example must be provided to the whole system by itself
"Structure Diagram"
"Primary Role"
Singleton defines a instance operation that allows the client to access its unique instance. Instance is a class method. The only instance that is responsible for creating it.
Disadvantages
1. Controlled access to a unique instance
2. Narrowing the single case pattern of namespaces is an improvement on global variables. It avoids the global variable pollution namespaces that store unique instances
3. Allow for operation and presentation of the essence of a single instance class can have subclasses. It is also easy to configure an application with an instance of this extended class. You can configure the application at run time using an instance of the class you need.
4. Allow variable number of instances (multiple case mode)
5, more flexible than class operation
Applicability
1. When a class can have only one instance and the customer can access it from a well-known access point
2, when this unique instance should be extensible through subclasses. And the user should be able to use an extended instance without changing the code.
"Singleton mode PHP instance"
Copy Code code as follows:
<?php
/**
* Single case mode
* -------------
* @author Zhaoxuejie <zxj198468@gmail.com>
* @package Design
* @version v1.0 2011-12-14
*/
Class Singleton {
Private static member variable, saving global instance
private static $instance = NULL;
Private construction method to ensure no direct instantiation of the outside world
Private Function __construct () {}
static method, which returns a unique instance of this class
public static function getinstance () {
if (!isset (self:: $instance)) {
$c = __class__;
Self:: $instance = new $c;
}
Return self:: $instance;
}
Test method
Public Function info () {
return ' OK ';
}
Prevent cloning
Public Function __clone () {
Trigger_error (' Clone is not allowed. ', e_user_error);
}
}
$s = singleton::getinstance ();
echo $s->info ();
?>