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