Initializing singleton in class instead of instanc

2019-09-21 14:31发布

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

3条回答
在下西门庆
2楼-- · 2019-09-21 15:20

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

查看更多
Lonely孤独者°
3楼-- · 2019-09-21 15:22

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.

查看更多
▲ chillily
4楼-- · 2019-09-21 15:24

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.
    }
}
查看更多
登录 后发表回答