Write a single example (Singleton) and illustrate the purpose and benefits of a single case __javasuan

Source: Internet
Author: User

The purpose of a single example is to ensure that a class has only a single instance, meaning that you cannot create a new instance of the class by using new.

The benefit of a single example: When an object can have only one instance inside the program, it guarantees that we don't create it repeatedly, but always point to the same object.

Singleton by restricting the construction method to private, the class is instantiated externally, and within the same virtual machine scope, the only instance of Singleton can be accessed through the getinstance () method.

First: Instantiate (also known as a Hungry Man singleton mode) when declaring a variable, the code is as follows:

public class Singleton {

private static Singleton instance = new Singleton (); has been instantiated by itself

Private Singleton () {}//proprietary default construction

public static Singleton getinstance () {//Static factory method

return instance;

}

}

The second: Put the creation of the object into the method (also known as the lazy single case pattern), the code is as follows:

public class Singleton {

private static Singleton instance = NULL;

Private Singleton () {}

public static synchronized Singleton getinstance () {

You can also write this: synchronized public static Singleton getinstance () {

if (instance = = null) {

Instance = new Singleton ();

}

return instance;

}

}

Their pros and cons:

The first type of a hungry man:

Advantages: When the class load initialization to create the object, call getinstance, there is no synchronization method, Run-time performance is high.

Disadvantages: Class loading is slow and takes up too much resource space.

The second type of idler:

Advantages: Avoid the shortcoming of the first way, at the same time, can run safely under multithreading.

Disadvantage: Because he uses the lock, the efficiency is slow in the operation.

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.