Three modes of a single case

Source: Internet
Author: User

The first form: The lazy type, is also the commonly used form.
public class Singletonclass
{
private static Singletonclass Instance=null;
public static synchronized Singletonclass getinstance ()
{
if (instance==null)
{instance=new singletonclass ();}
return instance;
}
Private Singletonclass () {}
}

//second form: A hungry man
 //some explanations for the first line of static
 //Java allows us to define static classes within a class. such as the inner class (nested classes). The
 //class that encloses the nested class is called an external class.
 //in Java, we cannot decorate the top level class with Static.
 //only the inner class can be static.    
 //defines an instance of itself within itself, for internal calls only   
 public static class singleton{
   private static final Singleton instance = new Singleton ();    
  private Singleton ()
  {        
   //do something    
  }    
  // This provides a static method for external access to this class, with direct access to the     
  public static Singleton getinstance () {
   return instance;}
 }

The third form: The form of a double lock.
public static Class singleton{
private static Singleton Instance=null;
Private Singleton () {
Do something
}
public static Singleton getinstance () {
if (instance==null)
{synchronized (Singleton.class) {
if (null==instance) {
Instance=new Singleton ();
}
}
return instance;
}
}//This mode will synchronize the content below the if inside, improve the efficiency of execution, do not have to synchronize every time to get the object, only the first time synchronization, created later is not necessary.

Three modes of a single case

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.