我有另一个面试问题.我觉得这很愚蠢,但也许有些东西我不知道了.问题是这是哪个GoF模式(答案:单身),如果有任何问题,我如何解决它们.
我没有看到任何问题.我提到这从未被释放过,我希望从这种模式中获得.这就是我所说的.我错过了什么吗?
public class Class1
{
private static Class1 oInstance = null;
private Class1() { }
public static Class1 GetInstance()
{
if (oInstance == null)
{
oInstance = new Class1();
}
return oInstance ;
}
}
Run Code Online (Sandbox Code Playgroud)
Sam*_*ron 13
请参阅:.NET的明显单例实现?
在实现Singleton模式时,您需要考虑多个问题.
以下是您可以遵循的良好通用模式.它的线程安全,密封,使用属性和延迟instaniates单身.
public sealed class Singleton
{
static class SingletonCreator
{
// This may seem odd: read about this at: http://www.yoda.arachsys.com/csharp/beforefieldinit.html
static SingletonCreator() {}
internal static readonly Singleton Instance = new Singleton();
}
public static Singleton Instance
{
get { return SingletonCreator.Instance; }
}
}
Run Code Online (Sandbox Code Playgroud)