Ensure that a class has only one instance and provide a global access point to it.
The singleton pattern has three characteristics:
1. A class has only one instance
2. It must create this instance by itself
3. You must provide this instance to the entire system yourself
1. Singleton pattern structure diagram
2. Main roles in singleton mode
Singleton defines an Instance operation that allows clients to access its only instance. Instance is a class method. Responsible for creating its only instance.
3. Advantages of singleton mode
1. Controlled access to unique instance
2. Reduce the namespace. The singleton mode is an improvement on global variables. It avoids polluting the namespace with global variables that store unique instances
3. Allows for the essence of operation and presentation. Singleton classes can have subclasses. And it is very easy to configure an application with an instance of this extended class. You can configure your application at runtime with instances of the classes you need.
4. Allow a variable number of instances (multiple instance mode)
5. More flexible than class operations
4. Applicable Scenarios of Singleton Mode
1. When a class can only have one instance and clients can access it from a well-known access point
2. When this only instance should be extensible through subclassing. And users should be able to use an extended instance without changing their code.
5. Singleton mode and other modes】
Factory method pattern: The singleton pattern uses the factory pattern to provide its own instances.
Abstract factory pattern (abstract factory pattern): The abstract factory pattern can use the singleton pattern to design the specific factory class into a singleton class.
Builder mode (Builder mode): The construction mode can design specific construction classes into singleton mode.
5. Singleton mode PHP example
<?php /** * 懒汉式单例类 */ class Singleton { /** * 静态成品变量 保存全局实例 */ private static $_instance = NULL; /** * 私有化默认构造方法,保证外界无法直接实例化 */ private function __construct() { } /** * 静态工厂方法,返还此类的唯一实例 */ public static function getInstance() { if (is_null(self::$_instance)) { self::$_instance = new Singleton(); } return self::$_instance; } /** * 防止用户克隆实例 */ public function __clone(){ die('Clone is not allowed.' . E_USER_ERROR); } /** * 测试用方法 */ public function test() { echo 'Singleton Test!'; } } /** * 客户端 */ class Client { /** * Main program. */ public static function main() { $instance = Singleton::getInstance(); $instance->test(); } } Client::main(); ?>
The above is the code to implement the singleton mode using PHP. There are also some conceptual distinctions about the singleton mode. I hope it will be helpful to everyone's learning.