I. Class Diagram
Ii. Intention
Ensure that a class has only one instance and provides a global access point to it.
Iii. Applicability
A) when the class can only have one instance and the customer can access it from a well-known access point.
B) when this unique instance should be extensible through subclass, and the customer should not need to changeCodeYou can use an extended instance.
IV. Implementation Method
1. Lazy Mode
Package Effece. Singleton;
// Lazy Mode
// It is not initialized until the first call.
Public Class Singleton1 {
Private Static Singleton1 instance = Null ;
Private Singleton1 (){
}
Public Static Synchronized Singleton1 getinstance (){
If (Instance = Null ){
Instance =New Singleton1 ();
}
Return Instance;
}
}
2. Hunger Mode
PackageEffece. Singleton;
//Hunger mode,
//Initial Plan upon declaration
Public ClassSingleton2 {
Private StaticSingleton2 instace =NewSingleton2 ();
PrivateSingleton2 (){
}
Public StaticSingleton2 getinstance (){
ReturnInstace;
}
}
3. Double Check Mode
Package Effece. Singleton;
// Double Check Mode
// Not secure: Http://www.ibm.com/developerworks/cn/java/j-dcl.html
Public Class Singleton3 {
Private Static Volatile Singleton3 instance = Null ;
Private Singleton3 (){}
Public Static Singleton3 getinstance (){
If (Instance = Null ){
Synchronized (Singleton3. Class ){
If (Instance = Null ){
Instance = New Singleton3 ();
}
}
}
Return Instance;
}
}
5. RuntimeClass Singleton Mode
Public ClassRuntime {
Private StaticRuntime currentruntime =NewRuntime ();
Public StaticRuntime getruntime (){
ReturnCurrentruntime;
}
Not explained: clear at a glance.