- /**
- *
- * User: jifei
- * Date: 2013-07-31
- * Time: 23:19
- */
- /**
- * Class Singleton
- * Singleton pattern, also called monad pattern, is a commonly used software design pattern. When applying this pattern, the class of the singleton object must ensure that only one instance exists,
- * fully embodies the idea of DRY (Don't Repeat Yourself).
- *
- * The idea of implementing the singleton pattern is: a class can return a reference to the object (always the same one) and a method to obtain the instance (must be a static method, usually using the name getInstance);
- * When we call In this method, if the reference held by the class is not empty, the reference will be returned. If the reference held by the class is empty, an instance of the class will be created and the reference of the instance will be assigned to the reference held by the class;
- * At the same time, we will also The constructor of a class is defined as a private method, so that code elsewhere cannot instantiate objects of the class by calling the constructor of the class. The only instance of the class can only be obtained through the static methods provided by the class.
- *
- * Application scenario: Suitable for scenarios where a class has only one instance. Database connection, logging, shopping cart
- * Disadvantages: PHP runs at the page level and cannot directly share memory data across pages.
- */
- class Singleton
- {
- //Save the private static member variable of the class instance
- private static $_instance;
- //Private constructor method
- private function __construct()
- {
- echo 'This is a Constructed method;';
- }
- //Create an empty private __clone method to prevent the object from being cloned
- private function __clone()
- {
- }
- //Single case method, used to get the only instance object
- public static function getInstance()
- {
- if (!(self::$_instance instanceof self)) {
- //instanceof is used to detect objects and classes affiliation, is_subclass_of whether the class to which the object belongs is a subclass of the class
- self::$_instance = new self();
- }
- return self::$_instance;
- }
- //Test
- public function test()
- {
- echo 123;
- }
- }
- $a = Singleton::getInstance();
- $a->test();
- echo PHP_EOL;
- $b = Singleton::getInstance(); //On the second call The constructor is not executed
- $b->test();
- echo PHP_EOL;
- //$c=new Singleton(); Since the constructor is private, this will report an error
- //$d=clone $a; Clone object Report an error
Copy code
|