Why is the singleton mode used in programming and development?
The existence of Singleton mode solves the problem of multi-thread concurrent access. Second, the system memory is reduced, the system operation efficiency is submitted, and the system performance is improved.
Code for Singleton mode:
1 public class printer {2 Private Static printer = NULL; // create a private global variable 3/* 4 * if multiple threads are accessed concurrently, lock the variable and wait in queue, only one user can use it at a time. 5 */6 public static synchronized printer getprinter () {7 if (printer = NULL) {// if it is null, create the instance 8 printer = new printer (); 9} 10 return printer; 11} 12/* 13 * The structure is privatized to ensure that only one instance 14 */15 private printer () {16 17} 18} is in use in the system}View code
From code analysis, the singleton mode first provides an accessible instantiated object. If this object is not available, the printer class creates one. If you encounter multi-threaded concurrent access with the keyword synchronized, lock the class that does not hold the object to the waiting state. After the thread task holding the printer ends, the threads in the waiting state can hold the instance one by one and operate on the method. Such a process is called the singleton mode in programming.
If the singleton mode is not used in the system, when multi-threaded access is encountered, printer will give the requested Class A new printer object in the memory, let the request classes do the print method. In this way, a large amount of memory will cause the system to slow down. Like the CPU of a computer, the system will feel very high, and the computer will not be able to die. Because the system's hardware facilities need to change a small amount, we can only come up with a way to save costs, that is, the singleton mode allows multithreading To Be In The waiting state, one by one to solve. In this way, it saves memory and submits the running cost. That is, the meaning of a singleton.
Why is the singleton mode used in programming?