What is a singleton mode: ensure that only one instance object exists for a class and provides a global access point;
Application Environment: when only one object, one instance, is needed
For example: WinForm can only create one form at a time, only when one instance object is needed
Code:
Public classsingleton{//Determine whether the instantiation of a class is unique through a static private variablePrivate StaticSingleton MYINSTANCD;PrivateSingleton () {}//defines a global method that provides external access to a class Public StaticSingleton getinstance () {//if empty, the object is instantiated, otherwise the object is returnedif(myinstancd==NULL) {MYINSTANCD=NewSingleton ();}returnMYINSTANCD;}}
Cons: in multi-threaded time Two threads simultaneous access is empty and multiple instances are created
workaround : Add lock
Public classsingleton{//Determine whether the instantiation of a class is unique through a static private variablePrivate StaticSingleton MYINSTANCD;//determine if locking ensures thread synchronizationPrivate Static ReadOnly ObjectMyLock =New Object();PrivateSingleton () {}//defines a global method that provides external access to a class Public StaticSingleton getinstance () {//when lock is locked, the thread hangs and no multiple instance objects appearLock(myLock) {//if empty, the object is instantiated, otherwise the object is returnedif(MYINSTANCD = =NULL) {MYINSTANCD=NewSingleton ();}}returnMYINSTANCD;}}
Reference
C # design mode (1) + single-case mode