Create pattern (iv) Singleton mode

Source: Internet
Author: User

A summary of a sentence

A class has only one instance and provides a global access point.

Plot

Last said, the cock silk Xiao Ming classmate and goddess completed the first date. The Goddess was glad that Xiaoming was preparing for his next date. Goddess another suitor, Xiao Gang, is going to go out with the goddess.

But the goddess on a person, facing the pursuit of two people, can only choose one. The other person can only say, sorry.

We use a singleton mode to demonstrate the above scenario.

Task One: Create goddess

We created the Goddess class using a singleton method, and let him have the first time about to be free, the rest is not empty.

 Public classGoddess {PrivateGoddess () {Console.WriteLine ("I'm free, let's go."); }        Private StaticGoddess _goddess; //Create a global access point         Public StaticGoddess Hellogoddess () {if(_goddess = =NULL) {_goddess=Newgoddess (); }            Else{Console.WriteLine ("I'm sorry, I don't have time."); }            return_goddess; }    }

First, we let his instance become private. So the external cannot be called.

Then we create a static variable to return the instance.

Finally, we create a global access point. To perform the operation.

Task two: Xiao Ming and Xiao Gang, respectively, invited the goddess

Xiao Ming first invited the goddess, then the young just invited the goddess.

Static void Main (string[] args)        {            Console.Write (" Xiao Ming invites the goddess:");             = goddess.hellogoddess ();            Console.Write (" Little just invited the goddess:")            ; = goddess.hellogoddess ();            Console.ReadLine ();        }

Let's see, run the results

Xiaoming arrived at the goddess. Xiao just lost.

This is the singleton mode if you intend to use the single thread all the time and not operate asynchronously. Then this is totally available.

But if we use an asynchronous operation to invoke it, this will not work. Let's modify the asynchronous operation below.

The Goddess class is not modified. Let's modify Xiaoming and Xiao Gang to make an asynchronous call operation.

Task one: To extract Xiao Ming and Xiao Gang into the pursuit category

The invoke operation is performed using the await asynchronous request. Because I am too lazy to modify the goddess of this class, so I added a waiting time.

 Public classSuitors { Public Async voidGo () {Task XM=xiaoming (); Task XG=Xiaogang (); awaitXM; awaitXG; }         Public AsyncTask xiaoming () {awaitTask.delay ( +); Goddess Girl=goddess.hellogoddess (); }         Public AsyncTask Xiaogang () {awaitTask.delay ( +); Goddess Girl=goddess.hellogoddess (); }    }

When I execute the Go method, I do two suitors at the same time. Then there is the following scenario.

The Goddess does not let go ~ ~ ~ but we know that the Goddess can only agree to a person's date. So let's change the Goddess class.

Task two: Modify the Goddess class using double lock mode
 Public classGoddess {PrivateGoddess () {Console.WriteLine ("I'm free, let's go."); }        Private StaticGoddess _goddess; Private Static Objectobj =New Object(); //Create a global access point         Public StaticGoddess Hellogoddess () {if(_goddess = =NULL)            {                 Lock(obj) {if(_goddess = =NULL) _goddess=Newgoddess (); Else{Console.WriteLine ("I'm sorry, I don't have time."); }                }            }            Else{Console.WriteLine ("I'm sorry, I don't have time."); }            return_goddess; }    }

Two if the middle of a lock, double lock. Lock locks the thread until execution is complete. Relevant lock knowledge can be viewed. Point Me

So, the result of our Goddess's execution becomes.

Xiao Ming classmate, smooth about to the goddess. And let the rival small just touched rebuff.

Summarize

The lock lock and the global access point are the main points, and this mode is still useful.

Common scenarios: an object to use Singleton mode must be global and unique.

Select key: If more than one instance of an object occurs, it will cause a logical or procedural error.

Create pattern (iv) Singleton mode

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.