Singleton)
The single-piece mode defines the fact that a class can only have one instance. It is useful for exposing read-only data, and there are also static methods that do not depend on instance data. Instead of creating a class instance every time, you can use a static method of the class to implement the single-piece mode. The application contains references to an existing instance,
If this is the first call to return the instance method, an instance will be created in single-piece mode and released to the caller using any required data and returned instance. The subsequent call only returns the existing instance, the life cycle of an instance is the application domain.
ASP.net usually refers to the life cycle of the domain Application object.
Class Singleton
{
Private static Singleton instance;
Private static int numOfReference;
Private string code;
Private Singleton ()
{
NumOfReference = 0;
Code = "Jackieli ";
}
Public static Singleton GetInstance ()
{
If (instance = null)
{
Instance = new Singleton ();
}
NumOfReference ++;
Return instance;
}
Public static int Reference
{
Get {return numOfReference ;}
}
Public string Code
{
Get {return code ;}
Set {code = value ;}
}
}
Here, you must note that the constructor should be privatized to prevent external instantiation of this class. The instance should be returned with static variables. This is to ensure that there is only one instance globally.
Of course, you can also define an attribute to return a unique instance.
Public static Singleton Instatnce ()
{
Get
{
If (instance = null)
{
Instance = new Singleton;
}
Return instance;
}
}