2011-12-12 100 views
-2

爲什麼你不能做到以下幾點?在類中而不是實例中初始化單例?

class foo { 
    private static foo instance = new foo(); 
    List <string> messages = new List<string>(); 


    private foo(){} 
    public static void doSomething(){..} 

} 

編輯:

我的意思是有沒有這樣做的差異:

class foo { 
    private static foo instance = new foo(); 
    List <string> messages = new List<string>(); 


    private foo(){} 
    public static void doSomething(){..} 

} 

class foo { 
    private static foo instance; 
    List <string> messages = new List<string>(); 


    private foo(){} 
    public static void doSomething(){..} 

    public foo getInstance(){ 
    if(instance!=null){ 
     return instance; 
    } 
} 
} 
+0

你不能做什麼?除了'doSomething'中缺少返回類型之外,這裏一切都很好。 – spender

回答

1

這是爲支持它的語言實現Singleton模式的非懶惰方法。這是完全可以接受的,特別是因爲它是實現線程安全Singleton的方法之一。但是,如果您的Singleton對象的開銷很大(請參閱lazy initialization),則可能不適合以此方式創建它。

如果您的代碼不能編譯,如otheranswers指出,您的doSomething方法的語法不正確。

1

你的方法doSomething()缺少返回類型。嘗試:

class Foo { 
    private static Foo instance = new Foo(); 
    List<string> messages = new List<string>(); 

    private Foo() { } 

    public static void doSomething() { 
     // Make any necessary accesses to "instance" here. 
    } 
} 
1

你可以,你剛纔並沒有給出返回類型doSomething()