Java Object-oriented _ single case design pattern

Source: Internet
Author: User

Singleton design Pattern: guarantees that a class has only one instance and provides a global access point to access it

1. Privatization of construction methods

2. Declaring an object of this class

3. Provide an external static method to obtain an object instance

Two ways of realization: A hungry man type and lazy type

under what circumstances should it be used? when there is no attribute in a class (the state of the object), the class is used very frequently as a tool class;

benefit: Save memory (because objects are constantly being created consumes memory)

1  Public classPractice14 {2     3      Public Static voidMain (string[] args) {4         //TODO auto-generated Method Stub5Single s=single.getinstance ();6 S.method ();7 }    8 }9 //a hungry man typeTen classsingle{ One     Private StaticSingle single=NewSingle (); A     PrivateSingle () {//construction method Privatization, in order to prevent the instantiation of objects outside of this class -          -     } the      Public StaticSingle getinstance () { -         returnSingle ; -     } -      Public voidmethod () { +System.out.println ("Method"); -     } + } A //Lazy Type at classsingle2{ -     Private StaticSingle2 single=NULL; -     PrivateSingle2 () {//Structuring Method Privatization -          -     } -      Public StaticSingle2 getinstance () { in         if(single==NULL){ -single=NewSingle2 (); to         } +         returnSingle ; -     } the      Public voidmethod () { *System.out.println ("Method"); $     }Panax Notoginseng}

Java Object-oriented _ single case design pattern

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.