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