I. Single thread
Package COM. WZS. design;/*** big talk design mode -- page214 Singleton mode ** @ author administrator **/public class Singleton {Private Static Singleton instance; public static Singleton getinstance () {If (null = instance) {instance = new Singleton ();} return instance;} public static void main (string [] ARGs) {Singleton singleton1 = Singleton. getinstance (); Singleton singleton2 = Singleton. getinstance (); If (singleton1 = singleton2) {system. out. println ("the two objects are the same instance. ");}}}
Ii. Multithreading
Package COM. WZS. three;/*** big talk design mode -- page214 Singleton mode (multi-threaded, dual lock) ** @ author administrator **/public class Singleton {Private Static Singleton instance; private Static string lock = "Lock"; public static Singleton getinstance () {If (null = instance) {synchronized (LOCK) {If (null = instance) {instance = new Singleton () ;}} return instance;} public static void main (string [] ARGs) {Singleton singleton1 = Singleton. getinstance (); Singleton singleton2 = Singleton. getinstance (); If (singleton1 = singleton2) {system. out. println ("the two objects are the same instance. ");}}}