You only need to create an instance of a class in your program, using singleton mode.
Application scenario: Runtime class, database connection pool, log management (ex: LOG4J)
Implementation principle: A class, the internal definition of the static variables of the class, and defines the static method to get the static variable; the access permission of the constructor is defined as private;
A hungry man singleton mode: (Created when class is loaded)
1 Public classSingleton {2 Private StaticSingleton instance =NewSingleton ();3 PrivateSingleton () {//access rights are private to prevent an instance of the class from being fetched out of the class through a constructor function4 ...5 } 6 Public StaticSingleton getinstance () {7 returninstance;8 } 9 Ten}
Lazy Singleton mode: (created only when you need to get it)
1 Public classSingleton {2 Private StaticSingleton instance = null;3 PrivateSingleton () {//access rights are private to prevent an instance of the class from being fetched out of the class through a constructor function4 ...5 } 6 Public StaticSingleton getinstance () {
7 if (instance = = null) {
8 instance = new Singleton ();
9}Ten returninstance;One } A -}
Lazy Singleton mode is not a problem in single-threaded, but multiple instances are created under multithreading. contrary to the original intention of the singleton model, there is a lazy singleton model with double retrieval mechanism.
Double-search mechanism of Lazy singleton mode:
1 Public classSingleton {2 Private StaticSingleton instance =NULL;3 PrivateSingleton () {4 ...;5 }6 Public StaticSingleton getinstance () {7 if(Instance = =NULL){8 synchronized(Singleton.class) {//Increase synchronization mechanism9 if(Instance = =NULL) {TenInstance =NewSingleton (); One } A } - } - } the}
Singleton mode (Java environment)