Self-taught articles-single case mode (10)

Source: Internet
Author: User


single case mode: divided into idle type and a hungry man type. The principle is simply that a class can only create one object and provide the user with it.

a hungry man type: 1. Create a Private object

2. Building a private constructed object

3. Provide a way to call this object externally

public class Singletest {

public static void Main (String [] args) {

Single S1 =single.getinstance ();

}

}

Class Single {

private static Single S = new single ();

Private single () {}

public static single getinstance () {

return s;

}

}

Lazy Type: public class Singletest {

public static void Main (String [] args) {

Single S1 =single.getinstance ();

}

}

Class single{

private static single s = null; Create a reference variable, but delay the creation of a class,

Private single () {}

public static single getinstance () {

if (s==null) {

Synchronized (Single.class) {//Lock to avoid creating multiple objects

if (s==null)

S=new single (); Delaying the establishment of objects in this place

}

}

return s;

}

}



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.