2017-07-05 155 views
0

嗨可以請別人告訴我如何實例化下面給出的單例類的正確方法?如何實例化Bill Pugh方法中實現的單例類?

public class BillPughSingleton { 

    private BillPughSingleton(){} 

    private static class SingletonHelper{ 
     private static final BillPughSingleton INSTANCE = new BillPughSingleton(); 
    } 

    public static BillPughSingleton getInstance(){ 
     return SingletonHelper.INSTANCE; 
    } 
} 
+1

您不能'Classloader'做這項工作給你。 – Flown

+0

我不太明白你在這裏問的問題。你有一個完美的實現單身模式在這裏(雖然內部類SingletonHelper不是真的需要)。你能進一步描述你遇到的問題嗎? –

回答

1

嘗試:

BillPughSingleton bill = BillPughSingleton.getInstance(); 
1

你可以重寫你的類單純地喜歡這一點,並沒有更多的需要SingletonHelper

public class BillPughSingleton { 

private static BillPughSingleton INSTANCE; 
private BillPughSingleton(){} 

public static BillPughSingleton getInstance(){ 
    if (INSTANCE==null) { 
     INSTANCE = new BillPughSingleton(); 
    } 
    return INSTANCE; 
} 

}

爲instansiate你可以試試這個:

BillPughSingleton instance = BillPughSingleton.getInstance(); 

你可以找到更多的另一個例子here