1. Notes
1 single case mode: Ensure that a class has only one instance, instantiate it and provide the system with this instance
2 Single case Pattern classification: Hungry Singleton mode (when class loads, instantiate an object to its own reference), Lazy singleton mode (the object is instantiated when the method that gets the instance is invoked, such as GetInstance) (Java Single example mode performance superior to lazy singleton mode, C + + generally use lazy single case mode)
3 single case mode elements:
A) Private construction method
b The private static reference points to its own instance
c) A public static method that takes its own instance as the return value
2. Examples
Hungry single case mode:
Copy Code code 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 Example mode:
Copy Code code as follows:
Package com.wish.modedesign;
public class Singleton {
Private Singleton () {
}
private static Singleton instance;
Note Thread safety when public static synchronized Singleton getinstance () {//Multiple threads
if (instance = = null) {
Instance = new Singleton ();
}
return instance;
}
}
Test class Driver.java
Copy Code code 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 Application Scenarios
1 The advantages of a single case model:
There is only one object in memory that saves memory space.
Avoid frequent creation of destruction objects, which can improve performance.
Avoid multiple occupancy of shared resources.
can be accessed globally.
2) Applicable scenario:
Objects that need to be frequently instantiated and then destroyed.
Objects that are too time-consuming or too expensive to create, but often used.
A stateful tool class object.
An object that frequently accesses a database or file.
4. Precautions when using
1 can not use reflection mode to create a single case, or you will instantiate a new object
2 Note thread safety issues when using lazy single example mode
3. Single case mode and lazy single case mode construction methods are private and therefore cannot be inherited, and some single case patterns can be inherited (such as registration mode)