Design pattern classification is more, here first to learn a singleton mode
Singleton mode : In a Java application, a singleton object can be guaranteed to exist in one JVM with only one instance of the object . Divided into a hungry man type, Raikhan type, etc.
Our upper and lower code:
1 Packagecom.learn.chap03.sec18;2 3 Public classSingleton1 {4 5 /**6 * Construction method Private 7 */8 PrivateSingleton1 () {9 Ten } One A /** - * A hungry man single-case implementation - */ the Private Static Final Singleton1 Single1=NewSingleton1 (); - - /** - * Static Factory mode + */ - Public Static Singleton1 getinstance (){ + returnSingle1; A } at -}
1 Packagecom.learn.chap03.sec18;2 3 Public classSingleton2 {4 /**5 * Construction method Private 6 */7 PrivateSingleton2 () {8 9 }Ten One /** A * Raikhan-type singleton implementation is instantiated at the time of the first call - */ - Private Static Singleton2single; the - /** - * Factory - */ + Public synchronized StaticSingleton2 getinstance () { - if(single==NULL){ + //instantiate the first call ASystem.out.println ("Instantiation at first call")); atSingle =NewSingleton2 (); - - } - returnSingle ; - } -}
1 Packagecom.learn.chap03.sec18;2 3 Public classTestsingleton {4 5 Public Static voidMain (string[] args) {6Singleton1 Singleton1 =singleton1.getinstance ();7Singleton1 Singleton2 =singleton1.getinstance ();8System.out.println ("A Hungry Man Type:" + (Singleton1 = =singleton2));9 TenTestsingleton T1 =NewTestsingleton (); OneTestsingleton t2 =NewTestsingleton (); ASystem.out.println (T1 = =T2)); - -Singleton2 Singleton3 =singleton2.getinstance (); theSingleton2 Singleton4 =singleton2.getinstance (); -System.out.println ("Lazy Type:" + (Singleton3 = =singleton4)); - - } + -}
Run results
A hungry man type: True
False
Instantiate the first call
Lazy Type: True
Attention:
The difference between the A hungry man and the lazy type is that the A hungry man type is instantiated when initializing a singleton, and the lazy type is instantiated only when the factory initialization method is first called, and no longer instantiated
Java's design pattern