A singleton pattern (Singleton pattern) is a very common design pattern. The core is to ensure that there is only one instance of the Singleton class in the system. There are a number of situations in the system that involve configuration data and the generation of unique sequence IDs.
Refer to the definition of "Zen in design mode":
Ensure a class have only one instance,and provide a global point of access to it. (Make sure that one class has an instance, and instantiate it yourself and provide it to the entire system.) )
The simple class diagram is as follows:
There are 8 ways to find a single case pattern by collecting and collating.
1, a hungry man (static constant)
Public class Singleton { privatestaticfinalnew Singleton (); Private Singleton () { } publicstatic Singleton getinstance () { return instance;} }
This is a very simple way to understand. The instance of Singleton is initialized directly when the class is initialized. The instance is then obtained through the getinstance () method. There is no problem with thread synchronization. But there is also a drawback is not to achieve the effect of lazy loading.
2, a hungry man (static code block)
Public class Singleton { privatestatic Singleton instance; Static { new Singleton (); } Private Singleton () { } publicstatic Singleton getinstance () { return instance;} }
A single-instance pattern of Java design patterns