1. Description
1) Singleton pattern: Make sure that there is only one instance of a class, instantiate it yourself and provide this instance to the system
2) Singleton pattern classification: singleton pattern (instanced an object to its own reference when the class is loaded), lazy singleton pattern (the object will be instantiated only when the method that obtains the instance is called, such as getInstance) (Java singleton Mode performance is better than lazy singleton mode, lazy singleton mode is generally used in C++)
3) Singleton pattern elements:
a) Private construction method
b) Private static reference points to its own instance
c) Public static method with its own instance as the return value
2. Example
Hunger Singleton Mode:
The code copy 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 singleton mode:
The code copy is as follows:
package com.wish.modedesign;
public class Singleton {
private Singleton(){
}
private static Singleton instance;
public static synchronized Singleton getInstance(){ // Pay attention to thread safety when multi-threading
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
Test class Driver.java
The code copy 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, saving memory space.
Avoiding frequent creation and destruction of objects can improve performance.
Avoid multiple occupations of shared resources.
Can be accessed globally.
2) Applicable scenarios:
Objects that need to be instantiated frequently and then destroyed.
Objects that take too much time or too much resource when creating objects, but are often used.
Stateful tool-like object.
Objects that frequently access databases or files.
4. Things to note when using
1) When using, you cannot create a singleton with reflection mode, otherwise a new object will be instantiated.
2) Pay attention to thread safety issues when using lazy singleton mode
3) The hungry singleton pattern and lazy singleton pattern construction methods are both private and therefore cannot be inherited. Some singleton patterns can be inherited (such as registered mode)