This article introduces three kinds of commonly used PHP design patterns: Singleton mode, Factory mode, observer mode, has a good reference value, followed by small series to see it
First, the singleton mode
The so-called Singleton pattern is that only one instance of this class exists in the application.
Typically, singleton mode is used in instances where only the database access object is allowed, thereby preventing multiple database connections from being opened.
A singleton class should include the following points:
Unlike ordinary classes, a singleton class cannot be instantiated directly, but only by its own instantiation. Therefore, to achieve such a restrictive effect, the constructor must be marked private.
In order for a singleton class to function without being instantiated directly, you must provide an instance of it. Therefore, the Singleton class must have a private static member variable that can hold an instance of the class and a corresponding public static method that can access the instance.
In PHP, in order to prevent the cloning of a singleton class object to break the above implementation form of the Singleton class, usually also provides an empty private __clone () method for the base.
Singleton mode ensures that a class has only one instance, and instantiates itself and provides this instance to the entire system.
Singleton mode is a common design pattern, in the computer system, the thread pool, cache, log objects, dialog boxes, printers, database operations, graphics card drivers are often designed as a single case.
The singleton pattern is divided into 3 kinds: Lazy Type single case, a hungry man type single case, registration type single case.
The singleton mode has the following 3 features:
1. There can be only one instance.
2. You must create this instance yourself.
3. This instance must be provided to other objects.
So why use PHP singleton mode?
A major application of PHP is the application of the database to deal with the scene, there will be a large number of database operations in an application, the database handle connection to the database behavior, using a singleton mode can avoid a large number of new operations. Because each new operation consumes both system and memory resources.