Java Singleton Mode

Source: Internet
Author: User

Java Singleton Mode
Concept: java Singleton mode is a common design mode. The Singleton mode can be written in several ways. Here we mainly introduce three types: the lazy singleton and ELE. Me Singleton modes have the following features: 1. A singleton class can only have one instance. 2. The Singleton class must create its own unique instance. 3. The Singleton class must provide this instance to all other objects. I. Lazy Singleton

public class Singleton {    private static Singleton uniqueInstance = null;    private Singleton() {       // Exists only to defeat instantiation.    }    public static Singleton getInstance() {       if (uniqueInstance == null) {           uniqueInstance = new Singleton();       }       return uniqueInstance;    }    // Other methods...}

 

Singleton limits the constructor to private to avoid class instantiation outside. Within the same Virtual Machine range, Singleton's unique instance can only be accessed through the getInstance () method. (In fact, the Java reflection mechanism can be used to instantiate classes whose constructor is private, which will basically invalidate all Java Singleton implementations. We will not discuss this issue here, so we may think that the reflection mechanism does not exist .) Ii. Hunger examples
// Lazy Singleton type. in the first call, instantiate your own public class Singleton {// private default constructor private Singleton () {}// note that there is no final private static Singleton single = null; // static factory method public static Singleton getInstance () {if (single = null) {single = new Singleton () ;}return single ;}}

 

When the class is created, a static object has been created for the system. It will not be changed in the future, so it is inherently thread-safe.

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.