A singleton model from C # angle lazy and a hungry man

Source: Internet
Author: User

Single-Case mode:

Key points: 1, a class has only one instance, 2, the class to create the instance itself, 3, the class itself to the entire system to provide this instance.

Code Show:

namespacesingleton{/// <summary>    ///Lazy single case, multithreading security///lazy, do not create an instance when the class loads, so the class loads faster, but the runtime gets the object at a slower speed/// </summary>     Public classLazysingleton {Private StaticLazysingleton instance =NULL; //Multithreading Security        Private Static ObjectLockObject =New Object(); PrivateLazysingleton () {Console.WriteLine ("private Lazysingleton ()"); }         Public StaticLazysingleton Instance {Get            {                //no need to lock each time to improve efficiency                if(Instance = =NULL)                {                    //Multithreading Security                    Lock(lockobject) {if(Instance = =NULL)                        {                            return NewLazysingleton (); }                    }                }                returninstance; }        }    }    /// <summary>    ///a hungry man single case///initialization is done at class load, so class loading is slow, but getting objects is faster/// </summary>     Public classEagersingleton {//readonly allocation of dynamic memory        Private Static ReadOnlyEagersingleton instance =NewEagersingleton (); PrivateEagersingleton () {Console.WriteLine ("private Eagersingleton ()"); }         Public StaticEagersingleton Instance {Get            {                returninstance; }        }    }    classProgram {Static voidMain (string[] args) {            varLazy =lazysingleton.instance; varEager =eagersingleton.instance; }    }}

A singleton model from C # angle lazy and a hungry man

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.