问题描述
为什么不能执行以下操作?
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.
这篇关于在类中初始化单例,而不是实例?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!