Initializing singleton in class instead of instanc

2019-09-21 15:16发布

问题:

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().