Lazy Singleton
The lazy Singleton class instantiates itself when it is referenced for the first time. The problem with this simple implementation is that each access to getinstance () requires a synchronization operation, and in fact the synchronization only makes sense during the first access.
Public class lazysingleton {
Private Static lazysingleton m_intance = NULL;
// Private constructor to avoid external instance Creation
Private lazysingleton (){
}
// Return the unique instance of this class by using the static factory method.
// It is initialized only when the instance is not initialized.
// Use the synchronized keyword to synchronize access to getinstance () by different threads.
Synchronized public static lazysingleton getinstance (){
If (m_intance = NULL ){
M_intance = new lazysingleton ();
}
Return m_intance;
}
}
Hungry Chinese Singleton
When the class is loaded, it will instantiate itself.
Public class eagersingleton {
// Private (static final) instance member. The singleton object is created when the class is loaded.
Private Static final eagersingleton m_instance = new eagersingleton ();
// Private constructor to avoid external instance Creation
Private eagersingleton (){
}
// Return the unique instance of this class by using the static factory method.
Public static eagersingleton getinstance (){
Return m_instance;
}
Registration form example
The registered Singleton class is designed by gof to overcome the disadvantages that neither the hungry Singleton class nor the lazy Singleton class can inherit.
This Singleton actually maintains a group of Singleton instances and stores these instances in a map (register). For registered instances, they are directly returned from the factory, if there is no registration, first register and then return.
Import java. util. hashmap;
Import java. util. Map;
Public class regsingleton {
// Register thin, used to store all registered instances
Private Static Map <string, regsingleton> m_registry = new hashmap ();
// Add an instance to the register when the class is loaded
Static {
Regsingleton x = new regsingleton ();
M_registry.put (X. getclass (). getname (), X );
}
// Protected default constructor
Protected regsingleton (){
}
// The static factory method returns the unique instance of the specified object to be registered;
// Return the directly retrieved items that have already been registered. For those that have not yet been registered, first register them, and then retrieve and return
Public static regsingleton getinstance (string name ){
If (name = NULL ){
Name = "regsingleton ";
}
If (m_registry.get (name) = NULL ){
Try {
M_registry.put (name, (regsingleton) class. forname (name). newinstance ());
} Catch (instantiationexception e ){
E. printstacktrace ();
} Catch (illegalaccessexception e ){
E. printstacktrace ();
} Catch (classnotfoundexception e ){
E. printstacktrace ();
}
}
Return m_registry.get (name );