One: Lazy type
1: Thread-safe double lock check mechanism
public class singleton{
Private Singleton () {}//privately constructed function, guaranteed not to be instantiated by the outside world (regardless of reflection)
private static Singlecton single = NULL;
public static Singlecton getinstance ()
{if (singleton = = null)
{
Synchronized (Singleton.class)
{if (singleton = = null)
Singleton = new Singleton ();
}
}
Return Singleton
}
}
2: Static inner class: thread safe, no lock
public class Singleton {
private Static Class lazyholder{
private static final Singleton INSTANCE = new Singleton ();
}
Private Singlecton () {}
public static final Singlecton getinstance ()
{
return lazyholder.instsnce;
}
}
Here's a summary of the static inner classes:
A: A static inner class that can access only static members of an external class.
B: Static inner classes can be instantiated
C: Static inner classes are generated as the class loads (static members are generated when the class loads)
Two: A Hungry man type:
public class singleton{
Private Singlecton () {}
Pribate static final Singlecton single = new Singleton ();
public static Singlecton getinstance ()
{
return single;
}
}
Design mode-Singleton mode (Java)