ArticleDirectory
- 1st implementation
- 2nd implementation
- 3rd implementation
What is Singleton )? Only one instantiated object can exist during the process. The Singleton mode is in object-oriented mode.ProgramIt is very common in design and implementsCodeNot long, so it is also a common question in the interview.
Note: The Singleton mode is required to generate only one instance, so we need to hide the constructor of this class and set it to private. We can create a static instance to check whether it has been instantiated.
1st implementation
Public class singleton1 {private singleton1 () {} Private Static singleton1 instance = NULL; public static singleton1 getinstance () {If (instance = NULL) instance = new singleton1 (); return instance ;}}
This section is secure in a single thread. If you want to write a multi-threaded program, when both threads determine that instace = NULL is true, they all go back to instantiate the instance, violating the singleton principle, therefore, we need to add a synchronization lock to ensure inter-thread security.
2nd implementation
Public class singleton1 {private singleton1 () {} private static object syncobj = new object (); Private Static singleton1 instance = NULL; public static singleton1 getinstance () {If (instance = NULL)/* the lock operation is time-consuming. This statement avoids the lock operation every time */{synchronized (syncobj) {If (instance = NULL) instance = new singleton1 () ;}} return instance ;}}
Code close to perfection, but it is cumbersome to write 3rd implementation
This facilitates Java static variable instantiation, that is, static constructors are called to initialize static variables and realize the singleton mode.
Public class singleton1 {private singleton1 () {} Private Static singleton1 instance = new singleton1 (); public static singleton1 getinstance () {return instance ;}}
However, the problem is that it is not decided by the programmer to instantiate all classes that require singleton. Instead, the compiler instantiates its static members when it first encounters the class. For details, see my other blog article: another solution to the initialization order of initialization is to write an internal class nested, which will be accessed only when getinstance is used, so we can control the calling of the static initialization function of nested.
Public class singleton1 {private singleton1 () {} Private Static singleton1 instance; public static singleton1 getinstance () {return nested. instance;} static class nested {static singleton1 instance = new singleton1 ();} public static void main (string [] ARGs) {singleton1 sing = singleton1.getinstance ();}}
Perfect ~!