jla*_*ang 8 c# singleton instance
从谁需要"得到一个API最终用户的角度来看一个实例"一个Singleton类的,你喜欢"获得" 一个在.Instance属性或"称之为" .GetInstance()方法?
public class Bar
{
private Bar() { }
// Do you prefer a Property?
public static Bar Instance
{
get
{
return new Bar();
}
}
// or, a Method?
public static Bar GetInstance()
{
return new Bar();
}
}
Run Code Online (Sandbox Code Playgroud)
RaY*_*ell 14
如果你想创建单例,你不能只在每个GetInstance调用或Instance属性getter 上返回新对象.你应该做这样的事情:
public sealed class Bar
{
private Bar() { }
// this will be initialized only once
private static Bar instance = new Bar();
// Do you prefer a Property?
public static Bar Instance
{
get
{
return instance;
}
}
// or, a Method?
public static Bar GetInstance()
{
return instance;
}
}
Run Code Online (Sandbox Code Playgroud)
你选择哪种方式并不重要.如果您更喜欢使用属性选择它,如果您更喜欢方法,它也可以.