1. Description
1) Singleton mode: Ensure that there is only one instance of a class, instantiate it yourself and provide this instance to the system
2) Singleton pattern classification: Hungry Singleton mode (class loading when instantiating an object to its own reference), Lazy singleton mode (the object is instantiated only if the method that gets the instance is invoked, such as getinstance) (in Java, the singleton mode performance is better than lazy singleton mode, the Lazy singleton mode is generally used in C + +)
3) Single-instance mode elements:
A) Private construction method
b) private static references point to their own instances
c) public static method that takes its own instance as the return value
2. Example
Hungry Singleton mode:
Copy CodeThe code is as follows:
Package com.wish.modedesign;
public class Hungrysingleton {
private static Hungrysingleton instance = new Hungrysingleton ();
Private Hungrysingleton () {
}
public static Hungrysingleton getinstance () {
return instance;
}
}
Lazy single-case mode:
Copy CodeThe code is as follows:
Package com.wish.modedesign;
public class Singleton {
Private Singleton () {
}
private static Singleton instance;
public static synchronized Singleton getinstance () {//Multi-threading pay attention to thread safety
if (instance = = null) {
Instance = new Singleton ();
}
return instance;
}
}
Test class Driver.java
Copy CodeThe code is as follows:
Package com.wish.modedesign;
public class Driver {
public static void Main (string[] args) {
Singleton S1 = singleton.getinstance ();
Singleton s2 = singleton.getinstance ();
System.out.println (S1==S2); True
}
}
3. Advantages and applicable scenarios
1) Advantages of Singleton mode:
There is only one object in memory that saves memory space.
Avoid frequent creation of destroyed objects, which can improve performance.
Avoid multiple uses of shared resources.
can be accessed globally.
2) Applicable scene:
Objects that require frequent instantiation and destruction.
Objects that are too time consuming to create objects, or that consume too much resources, but are often used.
A stateful tool class object.
An object that frequently accesses a database or file.
4. Precautions during use
1) You cannot create a singleton with reflection mode, or you will instantiate a new object
2) Beware of thread safety when using Lazy singleton mode
3) Hungry singleton mode and Lazy Singleton mode construction methods are private and therefore cannot be inherited, and some singleton patterns can be inherited (such as the registration mode)
Java Singleton mode usage and considerations