Concept:
Java The single case pattern is a common design pattern, there are several types of single-case pattern, here are three kinds: lazy type single case, a hungry man type single case
The singleton mode has the following characteristics:
1 , the Singleton class can only have one instance.
< /span> 2 , The Singleton class must create its own unique instance.
< /span> 3 , The Singleton class must provide this instance to all other objects.
One, lazy type single case
public class singleton { private static Singleton uniqueInstance = null; private Singleton () { // Exists only to defeat instantiation. } public static singleton GetInstance () { if (uniqueinstance == null) { uniqueinstance = new Singleton (); } return Uniqueinstance; } // other methods.}
Singleton by restricting the construction method to private to prevent the class from being instantiated externally, the unique instance of Singleton can only be accessed through the getinstance () method within the same virtual machine scope.
(In fact, the Java reflection mechanism is the ability to instantiate a class constructed as private, which basically invalidates all Java Singleton implementations.) This issue is not discussed here, and it is deceiving to assume that the reflection mechanism does not exist. )
Two, a hungry man type single case
Lazy Singleton class. Instantiate yourself public class Singleton {//private default constructor private Singleton () {}///Note that there is no final private at the time of the first call Static Singleton Single=null; Static Factory method public static Singleton getinstance () {if (single = null) {single = new Singleton (); } return single; }}
A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is inherently thread-safe.
This article is from the "Android IOS" blog, so be sure to keep this source http://lovely1133.blog.51cto.com/1612511/1694267
Java Singleton mode