C # design mode-single instance,

Source: Internet
Author: User

C # design mode-single instance,

The Singleton mode ensures that the specified class has only one instance at any time during the entire application lifecycle, and provides the client program with a global access point for the instance.

1. Classic Mode

namespace singleClass{    class OnlyOneClass    {        private OnlyOneClass() { }        private static OnlyOneClass instance;        public static OnlyOneClass getInstance() {            if (instance == null) {                    instance = new OnlyOneClass();                    return instance;            }            return instance;        }    }}

Analysis:

1) The private constructor makes it impossible to implement this class through new when it is called.

2) define a static variable class. its lifecycle is the same as that of the program. This static variable is used to save the instance of this class.

2) instantiate yourself through a static method and return the instantiated result, because this method first checks global instances and then determines whether to create them again to ensure that there is only one instance.

 

However, if this method encounters multi-thread concurrency, the problem arises. For example, when both threads A and B access this class at the same time, the first check is null, two instances are created at the same time, which violates the single-instance mode principle.

 

After improvement:

2. Commonly known as lazy Model

namespace singleClass{    class OnlyOneClass    {        private OnlyOneClass() { }        public string thisname;        private static OnlyOneClass instance;        private static object _lock = new object();        public static OnlyOneClass getInstance() {            if (instance == null) {                lock (_lock)                {                    if (instance == null)                    {                        instance = new OnlyOneClass();                        return instance;                    }                }            }            return instance;        }    }}

Resolution:

1) declare an object variable as a lock object

2) First, judge whether the instance variable is null. If it is not null, no lock is needed and the instance is directly returned.

3) If it is null, lock the object and continue to judge whether it is null, to prevent other threads from creating an instance before the lock. After the lock, the operation can be ensured in a thread.

 

3. Hunger Mode

class HungerClass{        private HungerClass() { }        private readonly static HungerClass instance=new HungerClass ();        public static HungerClass getInstance(){            return instance;        }    }
It can be seen that this mode has been instantiated after the class initialization, unlike the lazy mode above, when the getInstance () method is called, it is instantiated.
In this way, the thread security issue will be handed over to CLR.
 

4. Test

Demonstrate how to declare two OneClass classes, assign values to the thisname of only one of them, and then output the thisname of the two classes to see what the other class will do.
Class Program {static void Main (string [] args) {Console. WriteLine ("Get a instanc from OnlyOneClass! "); Try {OnlyOneClass one = OnlyOneClass. getInstance (); // The variable Console of the first class of one. writeLine (one. toString (); while (true) {string ins = Console. readLine (); if (ins! = "") {One. thisname = ins;} // only assign OnlyOneClass two = OnlyOneClass to the thisname of one instance. getInstance (); // The variable Console of the second two class. writeLine (one. thisname + "one"); // outputs the thisname Console of one instance. writeLine (two. thisname + "two"); // output the thisname Thread of the two instance. sleep (1000) ;}} catch (Exception e) {Console. writeLine (e. message);} Console. readKey ();}}}
 
We can see that both instances come from one instance.
 
 

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.