Use of Singleton mode in Java

Source: Internet
Author: User

Singleton Mode
As the name implies, it isProgramThere is only one instance of this class, which is equivalent to the global variable in C ++. This instance is initialized only once. Other Objects obtain this object through related methods:

The Singleton mode can be used in the following ways:

1. the constructor of a class is a private function, that is, other classes are not allowed to instantiate the class.

2. You have a static object of your own type as a globally unique object.

3. You have a method to obtain the static state of a unique object. object initialization can be put in this method.

Example:

Public Class {
Private Static a SA; // It must be static
Public static a instance () // It must be static; otherwise, it cannot be called directly through the class.
{
If (SA = NULL) {SA = new ();}
Return SA;
}
Private A () {// constructor of Privatization
//.....
}
Public void otherfunction (){
//.........
}
}

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.