2010-05-25 34 views

回答

2
public class Singleton 
{ 
    static readonly Singleton _instance = new Singleton(); 

    static Singleton() { } 

    private Singleton() { } 

    static public Singleton Instance 
    { 
     get { return _instance; } 
    } 
} 
1

直到最近,我才知道,辛格尔顿被许多人认为是一个反模式,应该避免。更清洁的解决方案可能是使用DI或其他功能。即使你单身去刚读了这个有趣的讨论,从C# in Depth转述 What is so bad about singletons?

2

: 有各种不同的方式实现在C#Singleton模式,从 不是线程安全的,完全懒洋洋地加载,thread-安全,简单和高性能的版本。

最好的版本 - 使用.NET 4的懒惰类型:

public sealed class Singleton 
{ 
    private static readonly Lazy<Singleton> lazy = 
     new Lazy<Singleton>(() => new Singleton()); 

    public static Singleton Instance { get { return lazy.Value; } } 

    private Singleton() 
    { 
    } 
} 

它的简单和表现良好。它还允许您检查实例是否已使用IsValueCreated属性创建,如果需要的话。

相关问题