Singleton mode, Mode
Lazy style:
Package org. burning. sport. design. pattern. singlepattern;/*** Singleton mode ---- lazy, instantiate yourself during the first call ** (in fact, the Java reflection mechanism can be used to instantiate classes whose constructor method is private, * This will basically invalidate all Java Singleton implementations. We will not discuss this issue here, so we may think that the reflection mechanism does not exist .) */Public class Singleton {// private constructor, which indicates that the object private Singleton () {} private static Singleton singleton = null cannot be created in the external new; // 1. obtain the static factory method of the Instance (thread unsafe) public static Singleton getInstance () {if (singleton = null) {singleton = new Singleton ();} return singleton ;} // 2. obtain the instance's static factory method (thread-safe) public static synchronized Singleton getSafeInstance () {if (singleton = null) {singleton = new Singleton ();} return singleton ;} // 3. double check lock public static Singleton getSafe2Instance () {if (singleton = null) {synchronized (Singleton. class) {if (singleton = null) {singleton = new Singleton () ;}} return singleton ;}// 3. this method of getting an instance is better than that of 1 or 2, which achieves thread security and avoids the impact of performance on public static final Singleton getSafe3Instance () {return LazyHolder. INSTANCE;} private static class LazyHolder {private static final Singleton INSTANCE = new Singleton ();}}
Hungry Chinese style:
Package org. burning. sport. design. pattern. singlepattern;/*** Singleton mode ---- The ELE. Me Singleton type. * When the class is created, a static object has been created for the system and will not be changed in the future, therefore, it is inherently thread-safe. */Public class Singleton2 {private Singleton2 () {} private static final Singleton2 singleton = new Singleton2 (); public static Singleton2 getInstance () {return singleton ;}}
Https://gitee.com/play-happy/base-project