The single state design pattern is also called a single case pattern:
1. Single State design mode meaning:
The main function of a single state pattern is to ensure that in object-oriented programming, a class can only have one instance object. As an object's creation pattern, the singleton pattern ensures that a class has only one instance, and instantiates it and provides it globally to the entire system. Instead of creating an instance copy, it returns a reference to an instance stored within a singleton class.
2. Three key points for a single mode:
① requires a static member variable that holds a unique instance of the class;
② constructors and cloning functions must be declared private to prevent the external program new class from losing the meaning of the single case pattern;
③ must provide a public static method (usually the GetInstance method) to access this instance, thus returning a reference to a unique instance.
Copy Code code as follows:
<?php
Class DB {
private static $obj = null; Declares a private, static member property $obj
Private Function__construct () {//proprietary constructor method that can only instantiate an object within a class
echo "Connect the database successfully <br>";
}
The public static function getinstance () {//is not able to get objects of this class through this static method
if (Is_null (self:: $obj))//If the $obj in this class is empty, the description has not been instantiated
Self:: $obj = new self (); Instantiate the object of this class
Return self:: $obj; Returns an object of this class
}
Public Function Query ($sql) {//Execute SQL statement to complete operation of the database
Echo $sql;
}
}
$db = Db::getinstance (); Only static method getinstance () can be used to get objects of the DB class
$db-> Query ("Select *from user"); Accessing members in an object
?>