Java mode single-instance mode:
If you look at a single case pattern, you will see two classic structures:
- A Hungry man type
1 Public class Eagersingle {2 Private Static New Eagersingle (); 3 Public Static Eagersingle getinstance () {4return instance; 5 } 6 }
This is called a hungry man because the static variable instance is initialized directly when the class is loaded.
2. Lazy Type
1 Public classLazystringlet {2 Private StaticLazysingle instance =NULL; 3 /**4 * Static Factory method5 */ 6PubliceStatic synchronizedLazysingle getinstance () {7 if(Instance = =NULL) {8Instance =NewLazysingle (); 9 } Ten returninstance; One } A}View Code
The lazy type is actually a kind of comparative image appellation. Now that you're lazy, you don't have to worry about creating an object instance. Will wait until the immediate use of the object instance will be created, lazy people, always can not shirk the time to actually do the work, so when loading the object does not create an object instance. (Excerpt from http://www.2cto.com/kf/201204/125917.html)
3. Two kinds of differences and advantages:
A hungry man, because the class is loaded when the instance is created, it will reduce the running time relatively;
Lazy, because of the getinstance () method to get the instance plus synchroized (lock) so it is thread-safe, so when the execution of multiple threads, it will be executed one at a time, so it is relatively slow on the run speed, but also because of the time when the thread enters the instance will be created , so it saves space.
Personal understanding: (temporary) singleton mode, only in the multi-threaded meaning, in the sequence structure of the program does not make much sense. There are not many opportunities for working with multi-threading, so this is not a very deep understanding.
A single-instance pattern of Java Design Patterns essays