Single-Case mode

Source: Internet
Author: User

Characteristics of the single-case mode:

1: A singleton class can have only one instance.

2: The Singleton class must create its own unique instance.

3: The Singleton class must provide this instance to all other objects.

to create a common way for a single case :

1: Static variable method, also known as lazy instantiation;

2: Double lock.

First: Static variable method

This is a very good way to understand that. NET's operating mechanism determines that static variables can form a single piece, and a static variable is a variable stored in memory. Its mechanism ensures that only one variable is present at a time. It is very easy for us to write a program like this:

1: This is absolutely no problem for a single-threaded program, such as running an ASP, the general Web site is basically not multi-threading, all the above examples are sufficient. But what if it's multithreaded? If there are two lines at the same time to start judging instance==null, if this is true, then two instances are created, which violates the principle of single piece. This can be modified as follows: (non-thread-safe singleton mode)

      Public classsingleton{/// <summary>       ///defines a static variable instance of itself, with a default value of NULL/// </summary>       Private StaticSingleton instance =NULL; /// <summary>       ///Private Constructors///all of them are not of the public type, because to avoid the occurrence of new Singleton () to produce more instances/// </summary>       PrivateSingleton () {}/// <summary>       ///To generate an instance method/// </summary>       /// <returns></returns>        Public StaticSingleton getinstance () {//instantiate a variable if the instance is not initialized           if(Instance = =NULL) {instance=NewSingleton (); }           returninstance; }}

2: This method initializes the class instance at the time of program initialization, and completes the generation of the single piece by using the static variable and the private construction method. This is called lazy instantiation because it is created whether you invoke this instance or not .

  Public classsingleton{#regionThread-Safe single-piece (static variable method)/// <summary>       ///define a static variable instance of itself, initialize the variable while the program is running///instance is applied to ReadOnly, and also to avoid re-assigning to instances. /// </summary>       Private Static ReadOnlySingleton instance =NewSingleton (); /// <summary>       ///Private Constructors///all of them are not of the public type, because to avoid the occurrence of new Singleton () to produce more instances/// </summary>       PrivateSingleton () {}/// <summary>       ///To generate an instance method/// </summary>       /// <returns></returns>        Public StaticSingleton getinstance () {returninstance; }       #endregion}

Second: Double locking:

We can make a change to Method 1, its disadvantage is non-thread safety, since there are shortcomings of course it is necessary to correct.

3: This method is a single-piece mode of wire program security, but it has to lock the object every time it generates a single piece , which is also a performance drain. It said that there are shortcomings to change, this method of course is no exception:

 Public classsingleton{#regionThread-Safe single-piece (Dual-lock Method 1: Thread-safe but poor performance)/// <summary>       ///defines a static variable instance of itself, with a default value of NULL/// </summary>       Private StaticSingleton instance =NULL; /// <summary>       ///creates a single Object object, which is also static read-only for locking functions/// </summary>       Private Static ReadOnly ObjectOlock =New Object(); /// <summary>       ///Private Constructors///all of them are not of the public type, because to avoid the occurrence of new Singleton () to produce more instances/// </summary>       PrivateSingleton () {}/// <summary>       ///To generate an instance method/// </summary>       /// <returns></returns>        Public StaticSingleton getinstance () {//when you get an instance, you lock the object and then decide if there is           Lock(olock) {//instantiate a variable if the instance is not initialized               if(Instance = =NULL) {instance=NewSingleton (); }               returninstance; }       }       #endregion}

4: This method in the generated instance, the first to determine whether it is empty, if not empty, do not lock the object directly return the object instance. At the same time this double lock is compared to the static method, one advantage is that its instantiation is deferred to the class, and it will only generate an instance of this class if it is called.  .

 Public classsingleton{#regionThread-Safe single-piece (Dual Lock Method 2: Thread safe and superior performance)/// <summary>       ///defines a static variable instance of itself, with a default value of NULL///instance is applied to ReadOnly, and also to avoid re-assigning to instances. /// </summary>       Private StaticSingleton instance =NULL; /// <summary>       ///creates a single Object object, which is also static read-only for locking functions/// </summary>       Private Static ReadOnly ObjectOlock =New Object(); /// <summary>       ///Private Constructors///all of them are not of the public type, because to avoid the occurrence of new Singleton () to produce more instances/// </summary>       PrivateSingleton () {}/// <summary>       ///To generate an instance method/// </summary>       /// <returns></returns>        Public StaticSingleton getinstance () {if(Instance = =NULL)           {               //when you get an instance, you lock the object and then decide if there is               Lock(olock) {//instantiate a variable if the instance is not initialized                   if(Instance = =NULL) {instance=NewSingleton (); }               }           }           returninstance; }       #endregion}

Summary: the above is a regular single-piece mode, in fact, not all cases are the same as above. In the application of the abstract factory, it is often combined with a single-piece mode to make the factory instance unique. In using abstract Factory mode to arm news components, I used the abstract factory, at that time in the abstract factory class instance generation did not combine a single piece mode, where I want to change. My program idea is this, there is an abstract factory base class Abstractfactoryclass, which contains a public static Abstractfactoryclass getinstance () method, The effect is to generate an instance of its derived class, which is done through reflection. The two derived classes are:Abstractfactory_china,abstractfactory_us. It is not possible to return an instance of Abstractfactoryclass directly in this case, because it is an abstract class, Cannot be directly new Abstractfactoryclass (). Let's take a look at the class diagram of these three classes:

The code is as follows: code because the base class is abstract class all without private constructors in the general program above, the case of generating abstract factory class derived class instances does not apply to static methods to construct a single piece, because you cannot initialize the class instance directly with new.

        //set abstract classes to static variables to avoid loading assemblies multiple times        Private StaticAbstractfactoryclass instance=NULL ; /// <summary>        ///creates a single Object object, which is also static read-only for locking functions/// </summary>        Private Static ReadOnly ObjectOlock =New Object();  Public StaticAbstractfactoryclass getinstance () {//apply a double lock to produce a factory single object            if(Instance = =NULL)            {                Lock(olock) {if(Instance = =NULL)                    {                        //get the current factory name                        stringFactoryname = configurationsettings.appsettings["Factoryname"].                        ToString (); if(Factoryname! ="") Instance= (Abstractfactoryclass) assembly.load ("abstractfactorycompent").                        CreateInstance (Factoryname); Elseinstance=NULL; }                }            }            returninstance; }

Single-Case 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.