Document directory
- Not long ago, I met an interview question, which gave me only one class object for the new instance. I didn't turn around for a moment. I came back to Google to check and realize that this could be answered in a disguised form in single-State mode.
Not long ago, I met an interview question, which gave me only one class object for the new instance. I didn't turn around for a moment. I came back to Google to check and realize that this could be answered in a disguised form in single-State mode.
Keyword: Singleton
The Singleton mode ensures that only one instance of a class exists in a Java application.
The Singleton mode generally has several forms:
The first form: defines a class. Its constructor is private. It has a static private class variable. When the class is initialized, use a public getinstance method to obtain its reference, and then call the method. Java code
- Public
Class
Singleton {
Private
Singleton (){}
// Define your own instance internally
// Note that this is private for internal calls only
Private
Static
Singleton instance =
New
Singleton ();
// Here is a static method for external access to this class, which can be accessed directly.
Public
Static
Singleton getinstance (){
Return
Instance;
- }
- }
Public class Singleton {private Singleton () {}// define your own instance internally // note that this is private for internal calls only Private Static Singleton instance = new Singleton (); // here is a static method for external access to this class. You can directly access public static Singleton getinstance () {return instance ;}}
Form 2: Java code
- Public
Class
Singleton {
Private
Static
Singleton instance =
Null
;
Public
Static
Synchronized
Singleton getinstance (){
// This method is better than above. You don't need to generate objects every time. It's just the first time.
// Generate instances during use, improving efficiency!
If
(Instance =
Null
)
- Instance =
New
Singleton ();
Return
Instance;
- }
- }
Public class Singleton {Private Static Singleton instance = NULL; public static synchronized Singleton getinstance () {// This method is better than above, so you do not need to generate objects every time, it is only the first time that an instance is generated/used, improving the efficiency! If (instance = NULL) instance = new Singleton (); Return instance ;}}
Other forms:
Defines a class. Its constructor is private and all methods are static.
It is generally considered that the first form is more secure.