The Singleton mode has the following features:
1. A singleton class can only have one instance.
2. The singleton class must create its own unique instance.
3. The singleton class must provide this instance to all other objects.
The Singleton mode ensures that a class has only one instance, and the instance is self-instantiated and provided to the entire system. In computer systems, driver objects of thread pools, caches, log objects, dialogs, printers, and graphics cards are often designed as Singleton. These applications have more or less resource manager functions. Each computer can have several printers, but only one Printer Spooler can be used to prevent two print jobs from being output to the Printer at the same time. Each computer can have several communication ports. The system should centrally manage these communication ports to prevent a communication port from being simultaneously called by both requests. In short, the singleton mode is selected to avoid inconsistencies and avoid multiple leaders.
Singleton mode design: only one object exists in the memory of a class.
Method:
1. In order to prevent other programs from creating this class object too much, prohibit other programs from creating this class object first.
2. To allow other programs to access this class object, define an object in this class.
3. To facilitate access to custom objects by other programs, some access methods can be provided externally.
Code embodiment:
1. Privatize constructors
2. Create an object in this class.
3. Provide a method to obtain the object.
Method 1: Initialize
| The code is as follows: |
Copy code |
|
Class Single {
Private Single (){}
Private static Single s = new Single ();
Public static Single getInstance (){
Return s;
}
} |
Method 2: The object is initialized only when it is called.
| The code is as follows: |
Copy code |
|
Class Single {
Private static Single s = null;
Private Single (){}
Public static Single getinstance (){
If (s = null ){
S = new Single ();
}
Return s;
}
}
// Call
Class SingleDemo {
Public static void main (String [] args ){
Single s1 = Single. getInstance ();
}
} |