Design Mode-singleton mode, design mode-Mode
The Singleton mode is a relatively simple mode in the design mode. It is mainly used to ensure that only one class instance exists in the program, so it is called a singleton.
This is similar to an enumeration class. An enumeration class is an instance of a limited number of classes. In extreme cases, that is, the finite number of enumerations is 1, which is the singleton mode.
The following describes two methods for a singleton:
- Lazy: As the name implies, a class instance is created when the class is loaded.
- Hungry Chinese Style: The instance is created only when the method is called, and there is a thread security problem.
// Hungry Chinese public class Singleton {// 1. private Singleton () {}// 2. create an instance internally and privatize private static Singleton instance = new Singleton (); // 3. set the get method to allow external instances to be created and set to static. The corresponding member variables are also declared as static public static Singleton getInstance () {return instance ;}}
Note the following:
// Lazy public class Singleton1 {private Singleton1 () {} private static Singleton1 instance = null; public static Singleton1 getInstance () {// generally, this parameter is not created, it is created only when the instance is called and the instance is null. // thread security issues may exist. if (instance = null) {instance = new Singleton1 ();} return instance ;}}
The difference from the hunger style is the instance creation time.