How can we ensure that one class can only have one instance?
In the case of multiple threads, how can this problem be solved? Using System;
Using System. Collections. Generic;
Using System. text;
Namespace Singleton
{
Class Singleton
{
// The constructor is private to ensure that it is not explicitly instantiated.
Private Singleton () {}
// Define attributes and return the singleton object
Private Static Singleton;
Public Static Singleton instance
{
Get
{
If (Singleton = Null )
Singleton = New Singleton ();
Return Singleton;
}
}
}
}
// Multi-threaded Singleton
Namespace Singletonmultithread
{
Class Singleton
{
Private Static Object Lockhelper = New Object ();
// The constructor is private to ensure that it is not explicitly instantiated.
Private Singleton () {}
// Define attributes and return the singleton object
Private Static Volatile Singleton = Null ;
Public Static Singleton instance
{
Get
{
If (Singleton = Null )
{
Lock (Lockhelper)
{< br> If (Singleton = null )
Singleton = New Singleton ();
}
}
Return Singleton;
}
}
}
}
// Classic Singleton implementation: Only applicable to non-argument Constructors (available attributes for extension)
Namespace Classicalsingleton
{
Sealed Class Singleton
{
Private Singleton () {}
// Inline initialization, followed by a static Constructor
Public Static Readonly Singleton instance = New Singleton ();
}
Class Program
{
Static Void Main ( String [] ARGs)
{
Singleton S1 = Singleton. instance;
Singleton S2 = Singleton. instance;
If ( Object . Referenceequals (S1, S2 ))
Console. writeline ( " The two objects are the same instance. " );
Else
Console. writeline ( " Two instances with different objects. " );
}
}
}