在类中初始化单例,而不是实例? [英] Initializing singleton in class instead of instance?

查看:525
本文介绍了在类中初始化单例,而不是实例?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能执行以下操作?

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


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

}
$ / pre

编辑:

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


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

}

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


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

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


解决方案

这是为支持它的语言实现Singleton模式的非懒惰方法。这是完全可以接受的,特别是因为它是实现线程安全的Singleton的方法之一。但是,如果您的Singleton对象昂贵(请参阅懒惰初始化)来创建,那么它可能不是如果你的代码没有编译,就像其他 答案指出,您的 doSomething 方法不正确。


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

解决方案

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.

这篇关于在类中初始化单例,而不是实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆