Single-piece mode:
Make sure that a class has only one instance and provides a global access point.
Generally, we can make a global variable to make an object accessible, but it cannot prevent you from instantiating multiple objects. The best way is to let the class itself be responsible for saving its unique instance. this class can ensure that no other instance can be created, and it can provide a method to access the instance.
Keywords:
Singleton: Separate
Structure:
Implementation 1:
Public Sealed ClassSingleton {StaticSingleton single =Null;PrivateSingleton (){//// Todo: add the constructor logic here//}Public StaticSingleton getinstance (){If(Single =Null) {Single =NewSingleton ();}ReturnSingle ;}}
This implementation is not safe. When multiple threads access it, the single = NULL value is true at the same time. In this case, two instances of Singleton are obtained.
Implementation 2:
Public Sealed Class Singleton { Static Singleton single = Null ; Static Readonly Object Padlock = New Object (); Private Singleton (){ // // Todo: add the constructor logic here // }Public Static Singleton getinstance (){ Lock (Padlock ){ If (Single = Null ) {Single = New Singleton ();}} Return Single ;}}
This implementation is secure for the thread. However, the lock judgment is required before each access, which consumes a lot of system resources. Therefore, the dual lock method is used for design.
Implementation 3:
Public Sealed Class Singleton {Static Singleton single = Null ; Static Readonly Object Padlock = New Object (); Private Singleton (){ // // Todo: add the constructor logic here // } Public Static Singleton getinstance (){ If (Single = Null ){ Lock (Padlock ){ If (Single = Null ) {Single = New Singleton ();}}} Return Single ;}}
Advantages:
- Singleton will ensure that only one instance of this class is available and that all references from this instance
- It is easy to modify. You only need to modify one location to ensure full update.
Disadvantages:
Before generating an instance, you must determine whether the instance exists.
Applicable scenarios:
The Singleton mode can be used when the class has only one instance.
Explanation:
Lock: Lock is to ensure that a thread is locatedCodeWhen another thread tries to enter the locked code, it waits until the object is released.