C # Singleton mode in Design Mode,

Source: Internet
Author: User

C # Singleton mode in Design Mode,

 

Singleton mode: A class has only one object (instance) in the memory, and provides a way to access or obtain this object globally.

I wrote a small example of my learning over the past two days, asked my colleagues some questions about the thread, and found some information on the Internet. Also made some low-level mistakes.

The output text in the vs2017 console is garbled. I found some methods on the Internet for no use. Finally, I found that the template was selected for my new project.. net core template, so garbled characters are output. You must learn the lesson.

Directly Add code

Demo class, Person. cs

Public class Person {// <summary> // instantiate a private static variable. The storage class's own instance /// </summary> private static Person _ person = null; /// <summary> /// constructor /// </summary> private Person () {Console. writeLine ("constructed a {0}", GetType (). name) ;}public static Person GetInstance () {if (_ person = null) _ person = new Person (); return _ person ;}}

Client code:

{  var person1 = Person.GetInstance();  var person2 = Person.GetInstance();  var person3 = Person.GetInstance();
Console.WriteLine("person1 == person2:{0}", object.ReferenceEquals(person1, person2));}

Output result:

The output is only once, and the two objects reference the same. It indicates that the singleton mode is correct.

 

Advanced:

Public class Person {// <summary> // instantiate a private static variable. The storage class's own instance /// </summary> private static Person _ person = null; /// <summary> /// constructor /// </summary> private Person () {Console. writeLine ("constructed a {0}", GetType (). name) ;}public static Person GetInstance () {if (_ person = null) _ person = new Person (); return _ person ;}}

Client call code:

{Person person1 = null; Person person2 = null; Person person3 = null; // output multiple times var thread1 = new Thread () => {person1 = Person. getInstance () ;}); var thread2 = new Thread () =>{ person2 = Person. getInstance () ;}); var thread3 = new Thread () =>{ person3 = Person. getInstance () ;}); thread1.Start (); thread2.Start (); thread3.Start (); Thread. sleep (1000); // wait until the sub-thread completes the Console. writeLine ("person1 = person2: {0}", object. referenceEquals (person1, person2 ));}

Output result:

The output is multiple times, and the references are not equal. It indicates that this class is instantiated multiple times, and the write in singleton mode is not completely correct, so let's add thread security verification.

 

Continue to advanced: 

Public class Person {// <summary> // instantiate a private static variable. The storage class's own instance /// </summary> private static Person _ person = null; /// <summary> /// as the lock object, use private, static, and read-only objects // </summary> private static readonly object _ obj = new object (); /// <summary> /// constructor /// </summary> private Person () {Console. writeLine ("constructed a {0}", GetType (). name) ;}/// <summary> /// obtain the unique instance object of the class /// </summary> public static Person GetInstance () {if (_ person = null) // first judge whether it is null {lock (_ obj) // determine whether another thread is using {if (_ person = null) // wait until other threads are used. Then, judge whether it is null {_ person = new Person () ;}} return _ person ;}}

Client call code:

{// Use a lock to lock objects: Use a private, static, and read-only object. Person person1 = null; Person person2 = null; Person person3 = null; // output var thread1 = new Thread () => {person1 = Person. getInstance () ;}); var thread2 = new Thread () =>{ person2 = Person. getInstance () ;}); var thread3 = new Thread () =>{ person3 = Person. getInstance () ;}); thread1.Start (); thread2.Start (); thread3.Start (); Thread. sleep (1000); // wait until the sub-thread completes the Console. writeLine ("person1 = person2: {0}", object. referenceEquals (person1, person2 ));}

Output result:

Once output, the reference is equal, indicating that the singleton mode is successful and thread security has been added.

Advanced 2

You can use a static constructor as the singleton mode:

Public class Person {// <summary> // instantiate a private static variable. The storage class's own instance /// </summary> private static Person _ person = null; /// <summary> /// constructor /// </summary> private Person () {Console. writeLine ("constructed a {0}", GetType (). name) ;}/// <summary> /// static constructor, only once // </summary> static Person () {_ person = new Person () ;}/// <summary> /// get the instance of the class /// </summary> public static Person GetInstance () {return _ person ;}}

Client code:

{// Use a lock to lock objects: use private, static, and read-only objects // use a static constructor to initialize the person object Person person1 = null; person person2 = null; Person person3 = null; // multiple threads can output var thread1 = new Thread () => {person1 = Person. getInstance () ;}); var thread2 = new Thread () =>{ person2 = Person. getInstance () ;}); var thread3 = new Thread () =>{ person3 = Person. getInstance () ;}); thread1.Start (); thread2.Start (); thread3.Start (); Thread. sleep (1000); // wait until the sub-thread completes the Console. writeLine ("person1 = person2: {0}", object. referenceEquals (person1, person2 ));}

Output result:

 

Once output, the reference is equal, and the static constructor can also be used as a single-instance mode implementation method.

 

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.