The Singleton mode is used to ensure that only one instance in a class is created and provides a global access pointer to the instance.
Don't talk nonsense, go to the code
Singleton
Public sealed class signton
{
Public static signton Singn = NULL;
Private Static readonly object padlock = new object ();
Private signton ()
{
}
Public static signton instance
{
Get
{
If (Singn = NULL)
{
/* The lock keyword can be used to ensure that the code block is running without being interrupted by other threads.
This is achieved by obtaining mutex locks for a given object during code block running. This implementation is secure for the thread.
In this case, the object instance is created by the first thread to enter, and the later thread (instence = NULL) is false.
No longer create object instances. However, this implementation method adds additional overhead and reduces performance */
Lock (padlock)
{
If (Singn = NULL)
{
Singn = new signton ();
}
Return Singn;
}
}
Else
{
Return NULL;
}
}
}
}
UML diagram of Singleton mode:
Advantages of Singleton mode:
1, Instance control:The Singleton mode prevents other objects from instantiating themselves and ensures that all objects access one instance.
2, Scalability:Because the class itself controls the instantiation process, the class has the corresponding scalability to change the instantiation process.
Disadvantages of Singleton mode:
1System overhead.Although the system overhead looks small, check whether the instance exists every time you reference this class instance. This problem can be solved through static instances.
2, Development obfuscation.When using an object in the singleton mode (especially defined in the class library), developers must remember that they cannot use the new keyword to instantiate the object. Developers cannot see the source code in the class library, so they are surprised when they find that they cannot instantiate a class.
3, Object lifecycle.In Singleton mode, no object destruction is proposed. In the development language that provides memory management (for example, the. netframework-based language), only the single-instance mode object can destroy the object instance itself, because only it has reference to the instance. In a variety of development languages, such as C ++, other classes can destroy object instances, but doing so will cause the pointer inside the singleton class to be unknown.