Initializing singleton in class instead of instance? [closed]

戏子无情 提交于 2019-12-13 09:22:08

问题


Why can you not do the following?

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


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

}

Edit:

I mean is there a difference between doing this:

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


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

}

or

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;
    }
 }
}

回答1:


This is the non-lazy method of implementing the Singleton pattern for languages that support it. It's perfectly acceptable to do this, especially since it's one of the ways of implementing a thread-safe Singleton. However, if your Singleton object is expensive (see lazy initialization) to create, then it might not be appropriate to create it in this manner.

If your code doesn't compile, as the other answers point out, your syntax for the doSomething method is incorrect.




回答2:


Your method doSomething() is missing a return type. Try:

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.
    }
}



回答3:


You can, you just didn't give a return type to doSomething().



来源:https://stackoverflow.com/questions/8479605/initializing-singleton-in-class-instead-of-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!