The A Hungry man type and the lazy type of java=== single-class design mode

Source: Internet
Author: User

 PackageCn.china; Public classSingle { Public Static voidMain (String[]args) {//S singles=s.getinstance ();//S singless=s.getinstance ();//System.out.println (singles==singless);Test tt=test.getinstance (); Test TTT=test.getinstance (); Tt.setnum (10); Ttt.setnum (20);        System.out.println (Tt.getnum ());    System.out.println (Ttt.getnum ()); }/*** Single-Class design pattern: * The problem solved is to ensure that the object uniqueness of a class in memory * How to ensure the uniqueness of the object? * 1. Do not allow other programs to create this class object with new. * 2. Create an instance of this class in this class. * 3. Provide a way for other programs to get the object * Step: * 1, privatize the class constructor * 2, create a class object in this class by new, define a common method, and return the created object. */    }//a hungry man typeclasss{Private StaticS single=NewS (); PrivateS () {} Public StaticS getinstance () {returnSingle ; }}classtest{Private intnum; Private StaticTest t=NewTest (); PrivateTest () {} Public StaticTest getinstance () {returnT; }     Public voidSetnum (intnum) {         This. num=num; }     Public intGetnum () {return  This. Num; }}//Lazy Typeclasssingle2{//class is loaded with no objects, the object is created only when the GetInstance method is called.     Private StaticSingle2 s=NULL; PrivateSingle2 () {} Public Staticsingle2 getinstance () {if(s==NULL) s=NewSingle2 (); returns; }}

java=== single-class design pattern a hungry man and lazy-type

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.