Java common Design Patterns-Singleton mode

Source: Internet
Author: User

Single-Case mode:

1: Lazy Type

Package com.design;
/* 1: Lazy type */
public class Singleton {
/**
* Private, do not allow instances to be obtained externally through singleton.instance
* Static method can only access static variables.
*/

private static Singleton instance;
Private, not allowed to instantiate externally
Private Singleton () {}
/**
* Multithreading calls this method, it is possible to create more than one instance, need to synchronize, but pay attention to the efficiency problem
* 1.instance is empty the code fragment that needs to create the object needs to be locked, i.e. @0
* 2. The code snippet for creating the object must be judged again (
* If A and B threads, A and B both enter @1, a gets the lock, and executes the code that created the object,
* then B gets the lock again, and if you don't add @2, create an instance.
* )
*
*/
public static Singleton getinstance () {
if (instance = = null) {//@0
@1
Synchronized (Singleton.class) {
if (instance = = null) {//@2
Instance = new Singleton ();
}
return instance;
}
}
return instance;
}
}

2. A Hungry man type:

Package com.design1;
/* 2: A hungry man type */
public class Singleton {
private static Singleton instance = new Singleton ();

Private Singleton () {}

private static Singleton getinstance () {
return instance;
}
}

Java common Design Patterns-Singleton 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.