What is the singleton design model?
Only one instance object is provided in a class for external access.
The Singleton design mode is divided into three implementation methods:
1. Hunger:
Package pattern. Singleton;
// Empty Chinese Singleton class. It has been self-instantiated during class initialization.
Public class singleton1 {
// Private default constructor. This class cannot be instantiated outside
Private singleton1 (){
}
// Self-instantiated
Private Static final singleton1 single = new singleton1 ();
// Static factory Method
Public static singleton1 getinstance (){
Return single;
}
}
2. Lazy style:
Package pattern. Singleton;
// Lazy Singleton class. instantiated during the first call
Public class singleton2 {
// Private default constructor
Private singleton2 (){
}
// Note that there is no final
Private Static singleton2 single;
// Instantiate only once (I instantiate it only when you use me)
Static {
Single = new singleton2 ();
}
// Static factory Method
Public synchronized static singleton2 getinstance (){
If (single = NULL ){
Single = new singleton2 ();
}
Return single;
}
}
The hungry Chinese Singleton class instantiates itself when it is loaded. Even if the loader is static, it will still instantiate itself when the hungry Chinese Singleton class is loaded. From the perspective of resource utilization efficiency, this is slightly worse than the lazy Singleton class. In terms of speed and response time, it is better than the lazy Singleton class.
3. Registration:
Package pattern. Singleton; import java. util. hashmap; import java. util. Map;
// Register the type of Singleton.
// Similar to the method in spring, register the class name and obtain it directly from it next time.
Public class singleton3 {
Private Static Map <string, singleton3> map = new hashmap <string, singleton3> ();
Static {
Singleton3 single = new singleton3 ();
Map. Put (single. getclass (). getname (), single );
}
// Protect the default constructor
Protected singleton3 (){}
// Return the unique instance of this type in the static factory Method
Public static singleton3 getinstance (string name ){
If (name = NULL ){
Name = singleton3.class. getname ();
System. Out. println ("name = NULL" + "---> name =" + name );
}
If (Map. Get (name) = NULL ){
Try {
Map. Put (name, (singleton3) class. forname (name). newinstance ());
} Catch (instantiationexception e ){
E. printstacktrace ();
} Catch (illegalaccessexception e ){
E. printstacktrace ();
} Catch (classnotfoundexception e ){
E. printstacktrace ();
}
}
Return map. Get (name );
}
// A schematic commercial Method
Public String about (){
Return "Hello, I am regsingleton .";
}
Public static void main (string [] ARGs ){
Singleton3 single3 = singleton3.getinstance (null );
System. Out. println (single3.about ());
}
}