Singleton mode is the simplest, but also very important, design pattern with the following advantages:
1. Singleton mode saves memory and improves performance, such as Sessionfactory in MyBatis, when the memory-intensive classes need to be frequently created for destruction.
2. When you need to do a single read and write to a file, for example, you can write only one Windows text file at a time, you need to use a singleton to avoid multiple reads and writes
The disadvantages are:
1. The singleton mode does not have an interface and it is difficult to expand it.
2. Not conducive to testing, no way directly from the interface to mock out an object out of the test
Finally, the main way to realize this is a hungry man mode and lazy mode. One of the lazy patterns can be subdivided into several, and later.
A Hungry Man mode code:
Public Class singleton{ // instantiate itself when classes are loaded, a hungry man mode privatestaticNew Singleton (); Private Singleton () {}; Public getinstance () { returnthis. Instance
Lazy mode and thread-safe code 1
PublicClass singleton{Private StaticClass Singletom Instance =NULL; PrivateSingleton () {}; Public StaticSingleton getinstance () {if(instance==NULL){ //Double detection lock lazy mode, if it is directly on the getinsance lock, because there are 99% of the situation is thread-safe, will increase performance consumption, it is only double detection lock, optimize the lock, so that the lock only in 1% of the situation to execute
synchronized(Singleton.class) {
if (singleton = = null)
New
returnthis
}
Lazy mode and thread-safe code 2
PublicClass singleton{//The method of static inner class should be because the ClassLoader mechanism makes the inner class not in the class
is instantiated when loaded, so it is possible Private StaticClass Singletomloader () {Private StaticSingleton instance =NewSingleton (); } PrivateSingleton () {}; Public Static FinalSingleton getinstance () {returnSingletomloader.instance}}
Summary: The bean in the spring container uses a singleton pattern, which controls the life cycle of its bean by the spring container, and if it is set to multiple cases, it is entrusted to the Java EE container for the life cycle of its objects.
Java design pattern-Singleton mode