This article will give you a detailed introduction of some basic usage from Java design mode to SingleTon mode. If you need to know, you can refer to it.
Type:Creation Design Mode
Intent:Ensure that a class has only one instance and provides a global access point to it.
Applicability:
- When a class can only have one instance and the customer can access it from a well-known access point
- When this unique instance should be extensible through subclass, and the customer should be able to use an extended instance without changing the code
Structure:
There are two common methods to implement the SingleTon mode in Java. The first is to write the constructor as private and create a static private object in the class, the getInstance method is used to obtain the object. The second method is to declare a static private variable in the class and get it through the getInstance method, however, you must set this method to thread-safe (with synchronized modified ).
Method 1
| The Code is as follows: |
Copy code |
Public class SingleTon {
Private static SingleTon instance = new SingleTon ();
Private SingleTon (){
}
Public static SingleTon getInstance (){
Return instance;
}
}
|
Method 2
| The Code is as follows: |
Copy code |
Public class Singleton {
Private static Singleton instance = null;
Public static synchronized Singleton getInstance (){
// You do not need to generate an object every time. The object is created only when it is used for the first time.
// Use the idea of lazy initialization
If (instance = null)
Instance = new Singleton ();
Return instance;
}
}
|
In general, the first method is safer. The second method is not safe. After all, it cannot be ensured that all Singleton class objects are obtained through the getInstance method. It is possible to directly create an object through Singleton instance = new Singleton.