Home>Article>Backend Development> What is singleton pattern?

What is singleton pattern?

藏色散人
藏色散人 forward
2019-04-15 16:04:42 4855browse



The Singleton pattern is a commonly used software design pattern. It contains only one special class called a singleton class in its core structure. The singleton mode can ensure that there is only one instance of a class in the system and that the instance is easy to access from the outside world, thereby facilitating control of the number of instances and saving system resources. If you want only one object of a certain class to exist in the system, the singleton pattern is the best solution.

How to ensure that a class has only one instance and that this instance is easy to access? Defining a global variable ensures that the object can be accessed at any time, but it does not prevent us from instantiating multiple objects. A better solution is to make the class itself responsible for saving its only instance. This class guarantees that no other instances are created, and it provides a method to access the instance. This is the pattern motivation behind the singleton pattern.

For example, during the development process of php, we created a db class (database operation class), then we hope that a database in a php file can only be connected once and only one database is needed in a php file. Object! Because connecting to the database multiple times will greatly reduce the execution efficiency of PHP. It will also bring huge system overhead!

Use singleton mode to encapsulate your database

query('test'); $db2 = db::getInstance(); //输出 : 连接数据库....执行sql命令关闭数据库连接....

//You can see that no matter how many times we obtain the db object, although their names are different, they all represent the same object! This implements the singleton pattern!



The above is the detailed content of What is singleton pattern?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:hcoder.net. If there is any infringement, please contact admin@php.cn delete
Previous article:What is factory pattern? Next article:What is factory pattern?