If you only need one class object to complete all the functions, you can design this class into a singleton mode. This ensures that this class can and can only instantiate one object
Class design pattern Singleton pattern:
Class design mode: how should we write the class.
Singleton mode: an object. A class instance.
How can we ensure that one class can only instantiate one object. Within the script cycle, only one class instance exists.
How can we write this class to ensure the existence of an object.
What can the Singleton mode do?
If you only need one class object to complete all the functions, you can design this class into a singleton mode. This ensures that this class can only instantiate one object.
For example, for database operations, it is enough to have an object.
If you want to design the class into a singleton mode, you need to solve the following problems:
1. how can I ensure that the class can only instantiate one object?
2. if a new object is generated, how can we ensure that the object cannot be cloned?
Steps:
1 First, prohibit users from using new to obtain new objects without restrictions.
Constructor privatization
The result is that the class cannot be instantiated outside the class, rather than being instantiated.
2. objects can only be instantiated within the class. Execute new in the class.
Define a static method in the class, and instantiate new in this method
In this way, you can call this method through the class to obtain the new object.
In this case, you can call getInstance () infinitely to obtain many objects.
However, if you need to obtain new objects, you must use the getInstance () method. Therefore, you can operate on getInstance () to ensure the Singleton.
3. modify getInstance ()
If you call this method for the first time, you should instantiate a new object.
If this method is not called for the first time, it indicates that the object already exists and does not need to be instantiated. The instantiated object is returned.
Add a static attribute to the class to save the instantiated object. by judging whether the object exists, you can know the first few times that this method is used:
4. get the object in the hexadecimal clone form:
Singleton mode design method: three private and one public.