The single example pattern presumably everybody already very familiar with, usually its realization way divides into the following two kinds:
Copy Code code as follows:
The lazy type realizes
public class singleton{
private static Singleton instance = NULL;
Private Singleton () {}
public static newinstance () {
if (null = = Instance) {
Instance = new Singleton ();
}
return instance;
}
public void dosomething () {
Do something ...
}
}
A Hungry man type
public class singleton{
private static Singleton instance = new Singleton ();
Private Singleton () {}
public static Singleton newinstance () {
return instance;
}
public void dosomething () {
Do something ...
}
}
In the use of simple mode, the lazy and a hungry man have different scenarios, if the creation of simple objects is very memory but not in the application to start is necessary, we usually use the lazy type, wait until the real need to use the simple to create it, If you want to use it immediately as the project starts we will use the A Hungry man mode in initializing to create the Simple object.
In both of these modes, if the A hungry man is not problematic in multi-threaded situations, because the JVM will only load the simple class once, the lazy may have the problem of repeatedly creating the simple object, which is thread-insecure.
Is there a way to make the A hungry man-style simple mode also thread safe? The answer must be yes, we usually use a synchronized lock to achieve, but this is more cumbersome to implement, we can use the JVM's class loading mechanism to implement. In many cases, the JVM has provided us with synchronization controls, such as:
A. Data initialized in the static{} block
B. When accessing final fields, and so on.
When the JVM does class loading, he guarantees that the data is synchronized, and we can do this:
Use class-level inner classes to create object instances within this inner class. In this way, as long as the class-level inner class is not used, he does not create an object instance, which enables lazy loading and thread safety.
Copy Code code as follows:
public class singleton{
An inner class that creates a simple object when the inner class is loaded
private Static Class singletonholder{
public static Singleton instance = new Singleton ();
}
Private Singleton () {}
public static Singleton newinstance () {
return singletonholder.instance;
}
public void dosomething () {
Do something
}
}
This enables thread-safe a hungry man simple mode.
In addition, we can implement the simple pattern by enumerating the types, which is also the recommended way.
Use an enumeration type to implement the single example pattern as follows:
Copy Code code as follows:
public enum singleton{
Defines an enumerated element, which is an instance of the singleton
Instance
public void dosomething () {
Do something ...
}
}
Ok, the single case mode is first introduced here.