Singleton mode ensures that a class has only one instance, and the instance Singleton mode is self-instantiated and provided to the entire system. The Singleton mode can only be used when there is a real "Single Instance" demand.
1 Class Singleton {
2 Private Static Singleton sing;
3
4 Private Singleton (){
5 }
6
7 Public Static Singleton getinstance (){
8 If (Sing = Null ){
9 Sing = New Singleton ();
10 }
11 Return Sing;
12 }
13 }
14
15 Public Class Test {
16 Public Static Void Main (string [] ARGs ){
17 Singleton sing = singleton. getinstance ();
18 Singleton sing2 = singleton. getinstance ();
19 System. Out. println (SING );
20 System. Out. println (sing2 );
21 }
22 }
However, this Singleton mode seems to have some problems. In the case of multi-thread concurrency, there may still be two Singleton cases in the IF (sing = NULL) judgment, to avoid this, you 'd better change it:
1 ClassSingleton {
2PrivateSingleton (){}
3Private StaticSingleton sing =NewSingleton ();
4Public StaticSingleton getinstance (){
5ReturnSing;
6}
7}
There is also a singleton ~
Use enumeration:
EnumSingleton {
Sing;
//Method
Public VoidTest (){
System. Out. println ("Singleton ");
}
}
Because each enumeration is a singleton by default
Thought it was over? No ~ Use static internal classes:
ClassSingleton {
Private Static ClassSingletoninner {
Private StaticSingleton sing =NewSingleton ();
}
PrivateSingleton (){}
Public StaticSingleton getinstance (){
ReturnSingletoninner. Sing;
}
}
The advantage of this is that you can call the internal class to create this Singleton only when the class is not created during loading.