Java Fundamentals-Singleton design pattern (lazy type)

Source: Internet
Author: User

1  Public classTest7 {2     //Main function3      Public Static voidMain (string[] args) {4Test7.getinstance (). function (9, 81);5     }6 7     //Private member Variable8     PrivateString name;9     Private intAge ;Ten     Private StaticTest7 test7; One  A     PrivateTest7 () { -     } -  the      Public StaticTest7 getinstance () { -         if(Test7 = =NULL) {//This trip is mainly to improve efficiency -             synchronized(Test7.class) { -                 if(Test7 = =NULL) { +Test7 =NewTest7 (); -                 } +             } A         } at         returntest7; -     } -  -     Private voidfunctionintNUM1,intnum2) { -System.out.println (NUM1-num2); -     } in  -      PublicString GetName () { to         returnname; +     } -  the      Public voidsetName (String name) { *          This. Name =name; $     }Panax Notoginseng  -      Public intGetage () { the         returnAge ; +     } A  the      Public voidSetage (intAge ) { +          This. Age =Age ; -     } $}

There is a getinstance () method in the above code;

This method embodies an important characteristic of the lazy type,

That is, the generation of the instance is null when the caller invokes it, the default initialization (private static Test7 test7;) .

Note : In the GetInstance () method, the 16th line if () conditional statement is set only to improve the efficiency of the Code.

Removing this line of code can still run, but for many instance objects to invoke the GetInstance () method, plus if statements can significantly improve execution speed

Java Fundamentals-Singleton design pattern (lazy type)

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.