This article introduces three common php design modes: Singleton mode, Factory mode, and observer mode, which are of great reference value, next, let's take a look at the small series. This article introduces three common php design modes: Singleton mode, Factory mode, and observer mode, which have good reference value. let's take a look at them below.
I. First, the singleton mode
The Singleton mode means that only one instance of this class exists in the application.
The Singleton mode is usually used in instances that only allow the database to access objects, thus preventing multiple database connections from being opened.
A singleton class should include the following:
Unlike normal classes, a singleton class cannot be directly instantiated, but can only be instantiated by itself. Therefore, to obtain such a restricted effect, the constructor must be marked as private.
To make a singleton class effective without being directly instantiated, you must provide such an instance for it. Therefore, the singleton class must have a private static member variable that can save the class and a public static method that can access the instance.
In PHP, to prevent the singleton class object from being cloned to break the preceding implementation form of Singleton classes, an empty private _ clone () method is also provided for the basics.
The Singleton mode ensures that a class has only one instance, and the instance is self-instantiated and provided to the entire system.
The Singleton mode is a common design mode. in computer systems, A thread pool, cache, log object, dialog box, printer, database operation, and graphics card driver is often designed as a singleton.
There are three Singleton modes: lazy singleton, hungry Singleton, and registered Singleton.
The Singleton mode has the following three features:
1. only one instance is allowed.
2. you must create this instance on your own.
3. this instance must be provided to other objects.
So why use the PHP Singleton mode?
One of the main application scenarios of PHP is the scenario where applications interact with databases. in one application, there will be a lot of database operations, and the database handles the connection to the database, the Singleton mode can avoid a large number of new operations. Because each new operation consumes system and memory resources.
For more articles about three common PHP design patterns, refer to the Chinese PHP website!