利用內部靜態類實現單例模式
public class Singleton
{
private Singleton(){ }
public static Singleton getInstance()
{
return Nested.instance;
}
//在第一次被引用時被加載
static class Nested
{
private static Singleton instance = new Singleton();
}
public static void main(String args[])
{
Singleton instance = Singleton.getInstance();
Singleton instance2 = Singleton.getInstance();
System.out.println(instance == instance2);
}
}
總結:
由於內部靜態類只會被加載一次,故該實現方式時線程安全的!