I. What is a singleton mode
In this case, we should consider the design of the singleton mode only if you want to keep one object at a time and you do not want to have more objects.
The primary function of Singleton mode is to ensure that only one instance of a class exists in a Java program.
The singleton pattern has many advantages, it can avoid the repetition creation of the instance object, not only can reduce the time cost of each object creation, but also can save the memory space;
The ability to avoid logic errors caused by operating multiple instances. If an object is likely to run through the entire application, and it acts as a global unified management control, then the singleton pattern may be a worthwhile choice.
Two. Characteristics of the Singleton mode
1. Singleton mode can have only one instance.
2. The Singleton class must create its own unique instance.
3. The Singleton class must provide this instance to other objects.
Three. Singleton mode vs Static Class
After knowing what a singleton pattern is, I think you will think of static classes, "Since you use only one object, why not simply use static classes?" "Here I'll compare the singleton mode with the static class.
1. The singleton can inherit and be inherited, the method can be override, and the static method can not.
2. Objects produced in a static method are freed after execution and then cleaned by the GC and do not persist in memory.
3. The static class is initialized at the first run, and the singleton pattern can have other options, which can be deferred loading.
4. Based on 2, 3, because a singleton object is often present in the DAO layer (for example, sessionfactory), if repeated initialization and release, it will occupy a lot of resources, and use singleton mode to the memory can be more resource-saving.
5. Static methods have higher access efficiency.
6. The singleton mode is easy to test.
A few misconceptions about static classes:
Myth One: Static methods reside in memory and instance methods are not.
In fact, specially written instance methods can reside in memory, while static methods require constant initialization and deallocation.
Myth Two: The static method on the heap (heap), the instance method on the stack (stack).
In fact, it is loaded into a special non-writable Code memory area.
Selection of static and Singleton pattern scenarios:
Scenario One: Do not need to maintain any state, only for global access, at this time more appropriate to use static classes.
Scenario Two: You need to maintain some specific status, which is more appropriate to use a singleton mode.
1, a hungry man model of a singleton model
public class singleton{ private static Singleton instance = new Singleton (); Private Singleton () {} public static Singleton newinstance () { return instance; }}
Note: initial instance of static is created once. If we write a static method in the Singleton class that does not need to create an instance, it will still create an instance early. and reduce the memory usage.
Cons: No lazy loading effect, which reduces memory utilization.
2. Lazy mode
public class singleton{ private static Singleton instance = null; Private Singleton () {} public static Singleton newinstance () { if (null = = instance) { instance = new Singleton (); } return instance;} }
Note: In singleton static property instance, only one instance is created when instance is null, and the constructor is private, ensuring that only one is created at a time, avoiding duplicate creation.
Disadvantage: Only in the case of single-threaded normal operation, in the case of multi-threaded, there will be problems. For example, when two threads are running at the same time to determine if the instance is empty, and if instance is indeed not created, then two threads will create an instance, so a lock is required to resolve the thread synchronization problem, as follows:
public class singleton{ private static Singleton instance = null; Private Singleton () {} public static synchronized Singleton newinstance () { if (null = = instance) { Instance = new Singleton (); } return instance;} }
3. Double check Lock
public class Singleton { private static Singleton instance = null; Private Singleton () {} public static Singleton getinstance () { if (instance = = null) { synchronized ( Singleton.class) { if (instance = = null) {//2 instance = new Singleton () ; }}} return instance;} }
Note: When instance is null, you need to get the synchronization lock and create the instance once. When an instance is created, there is no need to attempt to lock it.
Cons: Use double if to judge, complex, error prone.
4. Static internal class
public class singleton{ private static class singletonholder{public static Singleton instance = new Singleton ( ); } Private Singleton () {} public static Singleton newinstance () { return singletonholder.instance; }}
This approach also leverages the class loading mechanism to ensure that only one instance instance is created. It is the same as the A Hungry man mode, it also takes advantage of the class loading mechanism, so there is no problem of multithreading concurrency. Not the same, it is inside the inner class to create an object instance. In this case, as long as the application does not use an inner class, the JVM does not load the singleton class, nor does it create a singleton object, thus allowing lazy lazy loading. In other words, this approach can guarantee both lazy loading and thread safety.
5. Enumeration
Public enum singleton{ instance; public void Whatevermethod () {} }
There are common drawbacks to the four ways in which you can implement a single example:
1) Additional work is required for serialization, or a new instance is created each time a serialized object is deserialized.
2) You can use reflection to forcibly invoke the private constructor (if you want to avoid this, you can modify the constructor so that it throws an exception when creating the second instance).
While the enumeration class solves both of these problems, the use of enumerations in addition to thread-safe and anti-reflection call constructors also provides an automatic serialization mechanism that prevents the creation of new objects when deserializing. Therefore, the effective Java authors recommend the method used. In practice, however, it is rare to see someone write like that.
Summarize
This article summarizes five kinds of Java implementation of the single-case approach, of which the first two are not perfect, double-check lock and static internal classes can solve most problems, usually the most used in the work is also the two ways. Although the enumeration is a perfect solution to a variety of problems, but this kind of writing is somewhat unfamiliar. Personal advice is to use a third and fourth way to implement a singleton pattern without special needs.
"Java" Design model-five types of singleton models