design mode → Singleton mode

Source: Internet
Author: User

A hungry man mode of the singleton mode:

Sample Code ↓

1 classdemo{2        Private StaticDemo obj =NewDemo ();//Save this type of static private field in this class3       PrivateDemo () {}//privatization constructors make this class outside of the instantiation4  Public StaticDemo getinstance () {//Life public static method obtains instances of this class by this method5           if(obj==NULL)//determines whether an object is empty6obj =NewDemo ();7           returnobj;8       }9}

The above-mentioned scenario is called the A hungry man pattern because this way of implementing a singleton pattern is immediately created when the program loads into the Java virtual machine.

Cons: Affects the speed at which the loader is loaded.

Advantage: Faster when getting objects.

The lazy mode of the singleton mode:

Sample Code ↓

1 classdemo{2         Private StaticDemo obj;//Save this type of static private field in this class3        PrivateDemo () {}//privatization constructors make this class outside of the instantiation4         Public StaticDemo getinstance () {//Statementexposes a static method to obtain an instance of this class through this method5            if(obj==NULL)//determines whether an object is empty6obj =NewDemo ();7            returnobj;8 }9}

The above situation is called lazy mode because this way the program is loaded into the Java Virtual machine only declares a field does not create an instance until the first time the instance is created

Cons: The first time you get an instance is slower.

Advantages: It will not affect the loading speed of the program, reduce the user's waiting time.

PS: Above for personal understanding, if there is any wrong place, welcome the comments below to specify.

design mode → Singleton 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.