Design Mode-singleton instance
The Singleton mode is: Ensure a class has only one instance, and provide a global point of access to it. make sure that a class has only one instance and provides the instance to the entire system. The Singleton mode ensures that only one instance exists. Java has two forms:
Hungry Chinese singleton: class is instantiated when loaded.
Package com. zz. singleton;/*** hunger examples * @ author txxs **/public class HungrySingleton {// class is instantiated when loading private static HungrySingleton m_instance = new HungrySingleton (); // The constructor is privatized to prevent external users from directly instantiating private HungrySingleton () {}// obtain the Instance Object public static HungrySingleton getInstance () {return m_instance ;}} using the following methods ;}}
Lazy singleton: the object is instantiated only when the class is referenced for the first time.
Package com. zz. singleton;/*** LazySingleton example * @ author txxs **/public class LazySingleton {// The object is instantiated for the first time when the class is referenced. private static LazySingleton m_instance = null; // privatize the display of the constructor to ensure that the private LazySingleton () {}// method cannot be directly instantiated by the outside world, preventing the two threads from simultaneously accessing m_instancesynchronized public static LazySingleton getInstance () {if (m_instance = null) {m_instance = new LazySingleton ();} return m_instance ;}}
Advantages of Singleton mode:
1. There is only one instance to reduce memory expenses.
2. Reduce system performance overhead.
3. You can avoid simultaneous operations on the same resource.
Disadvantages of Singleton mode:
It is difficult to expand because subclass cannot be created.
Haha, I wrote a code by myself and referred to the great gods to learn from each other and make progress. Download