Single example is the simplest design mode, the use of self-needless to say, but write a simple case is also a test of a procedural ape foundation, which is why many interviewers are happy to let the interviewer write a single case, is so-called simple and not simple. Needless to say, the following Java to implement a variety of single-case bar.
1. A Hungry man mode
publicclass Singleton{ privatestaticnew Singleton(); privateSingleton(){} publicstaticgetInstance(){ return instance; }}
2. Lazy mode
publicclass Singleton{ privatestatic Singleton instance; privateSingleton(){} publicstaticgetInstance(){ ifnull){ new Singleton(); return instance; } return instance; }}
3. Thread-Safe single-case mode
publicclass Singleton{ privatestatic Singleton instance; privateSingleton(){} publicstaticgetInstance(){ ifnull){ new Singleton(); return instance; } return instance; }}
4. Double-checked thread-safe single-case mode
publicclass Singleton{ privatestatic Singleton instance; privateSingleton(){} publicstaticgetInstance(){ ifnull){ synchronized{ ifnull){ new Singleton(); return instance; } } } return instance; }}
5. The best thread-safe notation
publicclass Singleton{ privateSingleton(){} privateclass SingletonHolder{ privatestaticnew Singleton(); publicstaticgetInstance(){ return instance; } } publicstaticgetInstance(){ return SingletonHolder.getInstance(); }}
Java implements various types of singleton patterns