java-Single case design mode

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. Declare an object of this class

3, to provide a static method to obtain an object instance

When do I use it?

1, through the use of tools in the design of the class;

2, when there is no attribute in a class;

3. This class is used very frequently as a tool class.

Two different ways:

One, a hungry man type

1  PackagePractice1;2 //single-case mode3  Public classTest7 {4      Public Static voidMain (string[] args) {5Singleton s=singleton.getinstance ();6 S.method ();7     }8 }9 classsingleton{Ten     Private StaticSingleton singleton=NewSingleton ();//Create objects when defined One     PrivateSingleton () {//Structuring Method Privatization A     } -      Public StaticSingleton getinstance () {//provides a global access point to the external, static method -         returnSingleton; the     } -      Public voidMethod () {//test Method -System.out.println ("Method"); -     } +}

A hungry man in the creation of a class at the same time has created a static object for the system to use, no longer change, so it is thread-safe.

Second, lazy-type

classsingleton2{Private StaticSingleton2 singleton2=NULL; //not directly created when defining     PrivateSingleton2 () {}//Structuring Method Privatization     Public StaticSingleton2 getinstance () {if(singleton2==NULL) {Singleton2=NewSingleton2 (); }        returnSingleton2; }     Public voidMethod () {//test MethodSystem.out.println ("Method"); }}

java-Single case design 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.