Design Mode learning-single-piece Mode

Source: Internet
Author: User

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;
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.