Design Mode-singleton mode, design mode-Mode
Singleton mode-hunger Mode
1. privatize the constructor and do not allow external users to directly create private Singleton (){}
2. Create a unique instance private static Singleton instance = new Singleton () within the class ();
3. Provide a public static Singleton getInstance () {return instance} method for obtaining an instance };
public class Singleton{ private static Singleton instance=new Singleton(); private Singleton(){}
public staitc Singleto getInstance(){ return instance; } }
Singleton mode-Lazy Mode
1. constructor privatization
2. Create a static member variable for a unique instance of the class (null)
3. The difference between creating a static member for a single instance is the time when the instance is generated (when the class is loaded or when the class is used)
public class Singleton{ private Singleton(){}private static Singleton instance; public static Singleton getInstance(){ if(instance==null){
return new Singleton();
} else {
return instance;
}
}
Differences:
Hungry Chinese: declarations are directly instantiated at the same time. Features: the loading process is slow, but the process of getting objects at run time is fast and thread safety.
Lazy: Do not instantiate the statement. Features: It is faster to load classes, but it is slower to get objects during running, and the thread is not secure.