Single-Case mode

Source: Internet
Author: User

1. Single-case mode

It is characterized by:

1. The construction parameter is private and prevents other classes from instantiating it, that is, there is only one instance of a class

2. Use a static variable to save an instance of the class

3. Provide a global access point, using a public static method to instantiate it

The following is a single pattern code that supports multithreading:

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.Threading.Tasks;namespacedanlimoshi{ Public classDanli {//Private constructor, which cannot be created outside the instance        PrivateDanli () {}Private StaticDanli Danli; Private Static Objectx=New Object();//defines a mutex semaphore that guarantees the uniqueness of a multithreaded access to the static instance         Public StaticDanli Getdanli ()//define a public static method to get an object instance        {            if(Danli = =NULL)//The first thing to determine is whether the object is empty, and if it is not empty, no need to lock, save time            {                Lock(x)//ensure that multiple threads access the static instance's uniqueness                {                    if(Danli = =NULL) {Danli=NewDanli (); }                }            }            returnDanli; }         Public voidShow () {Console.WriteLine ("work in!!! "); }    }    classProgram {Static voidMain (string[] args) {Danli Danli=Danli.getdanli ();            Danli.show (); Console.WriteLine ("{0}", Danli.            GetHashCode ()); Danli Danli2=Danli.getdanli ();            Danli2.show (); //a hash function is used to quickly generate a number that corresponds to the value of an object (hash code)Console.WriteLine (Danli2. GetHashCode ());//a hash function of two objects, which means that there is only one instance of an address in memory//compares two objects for the sameConsole.WriteLine (Danli.        Equals (Danli2)); }    }}
single-case mode

Single-Case mode

Related Article

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.