C # Single Instance Design Mode

Source: Internet
Author: User

Implementation of Singleton Mode
The Singleton mode is implemented based on two main points:
1) do not directly use the class constructor, but also provide a public static method to construct the class instance. Generally, this method is named instance. Public ensures its global visibility, and static methods ensure that no extra instances are created.
2) set the class constructor to private, that is, to hide the constructor. Any method that attempts to create an instance using the constructor will report an error. This prevents developers from directly creating class instances by bypassing the above instance method.
You can use the above two points to completely control the creation of the class: no matter how many places need to use this class, they access the unique instance generated by the class. The following C # code shows two ways to implement the singleton mode. developers can choose either of them based on their preferences.
Implementation Method 1: Singleton. CS
Using system;
Class singletondemo
{

Private Static singletondemo thesingleton = NULL;
Private singletondemo (){}
Public static singletondemo instance ()
{

If (null = thesingleton)
{
Thesingleton = new singletondemo ();
}
Return thesingleton;
}
}

Void main (string [] ARGs)
{Singletondemo S1 = singletondemo. instance ();
Singletondemo S2 = singletondemo. instance ();
If (s1.equals (S2 ))
{Console. writeline ("See, only one 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.