Singleton mode is a common design mode. in the book "Java and mode", Dr. Yan macro makes a comprehensive summary of Singleton mode.
There are three Singleton modes: lazy Singleton, hungry Singleton, and registered Singleton.
The Singleton mode has the following features:
1. A singleton class can only have one instance.
2. The Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to all other objects.
Note: The following code comes from Dr. Yan Hong's book "Java and mode", which adjusts the writing of some classes (in line with java1.5's habits) and adds a test method.
I. Lazy Singleton
When the class is loaded, the unique instance has been created. This design pattern is easy to implement in Java and hard to implement in other languages.
/**
* Created by intellij idea.
* User: leizhimin
* Date: 2007-9-11
* Time: 14:57:08
* <> Singleton mode-Lazy Singleton
*/
Public class lazysingleton {
/**
* The Private Static object is not initialized during loading.
*/
Private Static lazysingleton m_intance = NULL;
/**
* Private constructor to avoid external instance Creation
*/
Private lazysingleton (){
}
/**
* The static factory method returns a unique instance of this class.
* Initialization is performed only when the instance is not initialized.
* @ Return lazysingleton
*/
Synchronized public static lazysingleton getinstance (){
If (m_intance = NULL ){
M_intance = new lazysingleton ();
}
Return m_intance;
}
}
Ii. Hunger examples
When the class is loaded, no Singleton instance is created. The instance is created only when the instance is requested for the first time, and is not created after the instance is created for the first time.
/**
* Created by intellij idea.
* User: leizhimin
* Date: 2007-9-11
* Time: 14:45:25
* <> Singleton mode-hunger and Chinese Singleton
*/
Public class eagersingleton {
/**
* The private (static final) instance Member is created when the class is loaded.
*/
Private Static final eagersingleton m_instance = new eagersingleton ();
/**
* Private constructor to avoid external instance Creation
*/
Private eagersingleton (){
}
/**
* The static factory method returns a unique instance of this class.
* @ Return eagersingleton
*/
Public static eagersingleton getinstance (){
Return m_instance;
}
}
Iii. Registration Form Singleton
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.
/**
* Created by intellij idea.
* User: leizhimin
* Date: 2005-9-11
* Time: 15:20:16
* <> Singleton mode-registration Singleton
*/
Public class regsingleton {
/**
* Register thin, used to store all registered instances
*/
Private Static map 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 a unique instance of the specified object to be registered;
* If you have already registered a domain name, you can directly retrieve it and return it if you have not registered it.
* @ Param name
* @ Return regsingleton
*/
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 );
}
/**
* A schematic commercial Method
* @ Return string
*/
Public String about (){
Return "Hello, I am regsingleton! ";
}
}
4. An application of Singleton Mode
This application is the configuration file management class. To run this example correctly, I first created a XXXX. properties file on drive C with the following content:
-------------------
User = root
Password = leizhimin
The configuration file management class code is as follows:
/**
* Created by intellij idea.
* User: leizhimin
* Date: 2005-9-11
* Time: 15:55:01
* Singleton application-singleton application-configuration file management
*/
Public class configmanager {
/**
* Full name of the property File
*/
Private Static final string pfile = "C: \ XXX. properties ";
/**
* File object variables corresponding to attribute files
*/
Private file m_file = NULL;
/**
* Last modification date of the property File
*/
Private long m_lastmodifiedtime = 0;
/**
* Attribute object variables corresponding to the property File
*/
Private Properties m_props = NULL;
/**
* This class may have a unique instance.
*/
Private Static configmanager m_instance = new configmanager ();
/**
* The private constructor is used to ensure that the external world cannot be directly instantiated.
*/
Private configmanager (){
M_file = new file (pfile );
M_lastmodifiedtime = m_file.lastmodified ();
If (m_lastmodifiedtime = 0 ){
System. Err. println (pfile + "file does not exist! ");
}
M_props = new properties ();
Try {
M_props.load (New fileinputstream (pfile ));
} Catch (ioexception e ){
E. printstacktrace ();
}
}
/**
* Static factory Method
*
* @ Return configmanager
*/
Synchronized public static configmanager getinstance (){
Return m_instance;
}
/**
* Get the attribute configuration item Value
*
* @ Param name
* @ Param defaultval
* @ Return object
*/
Public final object getconfigitem (string name, object defaultval ){
Long newtime = m_file.lastmodified ();
If (newtime = 0 ){
// The property file does not exist.
If (m_lastmodifiedtime = 0 ){
System. Err. println (pfile + "file does not exist! ");
} Else {
System. Err. println (pfile + "file was deleted! ");
}
Return defaultval;
} Else if (newtime> m_lastmodifiedtime ){
M_props.clear ();
Try {
M_props.load (New fileinputstream (pfile ));
} Catch (ioexception e ){
E. printstacktrace ();
}
}
M_lastmodifiedtime = newtime;
Object val = m_props.getproperty (name );
If (val = NULL ){
Return defaultval;
} Else {
Return val;
}
}
}
Test Configuration File class:
/**
* Created by intellij idea.
* User: leizhimin
* Date: 2007-9-11
* Time: 16:42:45
* Configuration file management test
*/
Public class test_configmanager {
Public static void main (string [] ARGs ){
Configmanager cfgm = configmanager. getinstance ();
Object val1 = cfgm. getconfigitem ("SDF", "leizhimin ");
Object val2 = cfgm. getconfigitem ("user", "leizhimin ");
System. Out. println (val1.tostring ());
System. Out. println (val2.tostring ());
}
}
Running result:
Leizhimin
Root
Process finished with exit CoDe 0
5. Implementation of a single JDBC database tool class written by the author
/**
* Created by intellij idea.
* User: leizhimin
* Date: 2005-9-11
* Time: 18:04:46
* Application of Singleton mode in JDBC programming, used to design database tools
*/
Public class dbutil {
// Single Instance
Private Static final dbutil _ instance = new dbutil ();
// JNDI of the Data Source
Private Static final string datasource = "Java: COMP/ENV/jdbc/zvfims ";
/**
* Private constructor to prevent external instantiation
*/
Private dbutil (){
}
/**
* Database tool instance Factory
*
* @ Return dbutil
*/
Public dbutil getinstance (){
Return _ instance;
}
/**
* Business method: used to obtain database connections
*
* @ Return connection
*/
Public connection makeconnection (){
Connection conn = NULL;
Try {
Context CTX = new initialcontext ();
Datasource DS = (datasource) CTX. Lookup (datasource );
Conn = Ds. getconnection ();
} Catch (namingexception e ){
System. Out. println ("An error occurred while obtaining the data source. Please configure the JNDI data source of appserver! ");
E. printstacktrace ();
} Catch (sqlexception e ){
System. Err. println ("An error occurred while obtaining the database connection! ");
E. printstacktrace ();
}
Return conn;
}
}
This Singleton class and open business method can provide database connections for the entire system application.