<span style= "font-family:arial, Helvetica, Sans-serif; Background-color:rgb (255, 255, 255); " ></span>
The English original of the singleton mode is: Ensure a class has only one instance, and provide a global point of access to it. This means ensuring that a class has an instance and provides this instance to the entire system. The singleton mode is primarily to ensure that only one instance exists. There are two forms of representation in the Java language:
A hungry man singleton: classes are instantiated when they are loaded.
Package com.zz.singleton;/** * A hungry man single case * @author TXXS * */public class Hungrysingleton {//class is instantiated at load time private static hungrysing Leton m_instance = new Hungrysingleton ();//construction privatization to ensure that the outside world cannot directly instantiate private Hungrysingleton () {}//Gets the instance object public static by the following methods Hungrysingleton getinstance () {return m_instance;}}
Lazy Singleton: The object is instantiated only when the class is referenced for the first time.
Package com.zz.singleton;/** * Lazy Singleton * @author TXXS * */public class Lazysingleton {//The first time a class is referenced, object instantiation private static Lazysi Ngleton m_instance = null;//privatization of the constructor display ensures that the private Lazysingleton () {}//method synchronization cannot be instantiated directly by the outside world, preventing simultaneous access of two threads to m_ instancesynchronized public static Lazysingleton getinstance () {if (m_instance = = null) {m_instance = new Lazysingleton ();} return m_instance;}}
Advantages of Singleton mode:
1, only one instance, reduce memory expenditure.
2, reduce the performance cost of the system.
3. You can avoid simultaneous operation of the same resource.
Disadvantages of the Singleton pattern:
Unable to create subclass, expansion difficulty.
Haha, I wrote a code, reference to the great God, learn from each other progress, download
Design Pattern--Singleton (Singleton) example