C # Singleton mode [Singleton] Late night chat

Source: Internet
Author: User

It's a little too much to remember. The singleton pattern (also known as a single-piece mode) is at what time, sometimes the things that are not commonly used are often forgotten, and even gradually removed from the brain. Don't gossip, go straight to the chase.

What is a singleton mode?

Ensure that the specified class has only one instance at any time throughout the lifetime of the application and provides a global access point for the client to get the instance.

What is the role of singleton mode?

The specified class will only be created once throughout the application.

We then use code to deepen our understanding of the singleton pattern. Before that, we all know that if a class can be instantiated multiple objects without using singleton mode, such as the following code:

Here I first create a class:

1   Public class Person2 {3          Public stringName {Get;Set; }4          Public stringEmail {Get;Set; }5          Public intAge {Get;Set; }6}

In the application, I can instantiate this object infinitely according to my own needs.

Static void Main (string[] args) {     for (int0; i++ )     {          New Person ();     }}

At this point we begin to bring in the idea of Singleton mode, first of all we think about how to implement this class will only be able to instantiate one object at a time. The reason we can now infinitely go to new is because the class currently has a default public constructor, and anyone can get it.

It to make a new instantiation. Therefore, this also brings us a solution to the problem of thinking. Looking at the code below, I overwrite the default public constructor in my class, write a constructor and then try to change the access modifier to private

 public  class   person {  person () {}  public  string  Name {get ; set          public  string  Email {get ; set          public  int  Age {get ; set     

This time there is a problem when you create this object externally. ".... Not accessible because of ... Subject to the insured level limit

This time, although it is not possible to create this object in the outside world, we can still create objects through the inside of the class. (a method can be defined in a class that is used to create this object) so that we can create objects directly from the outside world by means of this class.

It is important to note that the method in which we define the creation of an object in a class must be a static method, so that the outside world can only use this class to instantiate an object, without needing to re-invoke the internal method with a new object. The code is as follows:

classprogram{Static voidMain (string[] args) {person P1=person.getinstance (); }} Public classPerson {PrivatePerson () {} Public StaticPerson getinstance () {return NewPerson (); }         Public stringName {Get;Set; }  Public stringEmail {Get;Set; }  Public intAge {Get;Set; } }

This time there is still a problem, we can still create n this object. This is not the same as the idea of a singleton model. Next we can continue to add an object in this class to judge, see the following code

1  Public class Person2     {3         PrivatePerson ()4         {5              6         }7         Private StaticPerson _instance =NULL;8  9          Public StaticPerson getinstance ()Ten         { One             if(_instance = =NULL) A             { -                 return NewPerson (); -             } the             return_instance; -             -         } -          Public stringName {Get;Set; } +          Public stringEmail {Get;Set; } -          Public intAge {Get;Set; } +}

At this time we are adding static members to this class, while static members share only one class in the application, and when the first call to the getinstance () method is null, then a new object is returned to the user when the condition is met. When the second time comes in, it will not be null, directly

Returns the object of the first time to the user. Let us test the prototype of this singleton pattern, test results:

This completes a basic singleton pattern, but it's completely imperfect. After all, this implementation does not meet the multi-threaded scenario. First of all, put aside this question, first summarizes the implementation of the following single-case model:

The outside world that makes the constructor private can not be called casually, and then creates a method in the class itself, in which the new object is created, because the method is to be a new object, so this method cannot be an instance method, only a static method.

Each time a static method is called it will be new once, so it is not a singleton pattern, so you need to add a static field to the class that is the type of the class itself. The static field is then judged in this class as NULL for the instance

An object, and then return. The next time you call it, it won't be null.

Well, to this side has solved our first problem. Time too fast, (almost 12:30!!) Hold on! People are a bit cheap, play games to watch TV do not care how late, want to serious write an article on the attention of time) next see how to deal with multi-threaded single-case mode.

1  Public classSingleton2     {3         4          PublicSingleton ()5         {6Console.WriteLine (".");7         }8         Private StaticSingleton _instancce;9         Private Static ReadOnly ObjectSYN =New Object();Ten          Public StaticSingleton getinstance () One         { A  -             if(_instancce = =NULL)//lock When object is null -             { the                 Lock(SYN)//Lock -                 { -                     if(_instancce = =NULL)//prevent simultaneous access by multiple threads -                     { +_instancce =NewSingleton (); -                         return_instancce; +                     } A                    at                 } -             } -             return_instancce; -              -         } -}

This is a lock-in way to handle multi-threaded access problems, the code is not difficult. Here's a simple explanation of why there are two objects to judge, first from the first object, because once locked, the code will be locked at the same time only a piece of code is executed, which will affect the performance of code execution. Therefore, before locking to determine whether the object is null, the second reason is null because the first judgment is not in this thread, indicating that as long as the condition can be entered, then the reason for reference to the above code comment.

I thought there was another way to get to sleep. A singleton mode can be implemented using a C # static field that initializes the feature only once when the class is first used. The code is as follows:

1  Public classSingleton22     {3         4         PrivateSingleton2 ()5         {6Console.WriteLine (".");7         }8 9          Public Static ReadOnlySingleton2 _instance =NewSingleton2 ();Ten          Public StaticSingleton2 getinstance () One         { A             return_instance; -         } -}

All right, here we go. ~good 9

C # Singleton mode [Singleton] Late night chat

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.