c# - 正确的单例类实现

标签 c# class design-patterns properties

我从单例类开始学习设计模式。您能解释一下以下实例属性实现之间的区别吗?

public class Singleton
{
    private static Singleton _instance;
    public static Singleton Instance => _instance ?? (_instance = new Singleton());
}
public class Singleton
{
    public static Singleton Instance => _instance.Value;

    private static readonly Lazy<Singleton> _instance =
        new Lazy<Singleton>(() => new Singleton());
}

最佳答案

自从 GoF 书中首次介绍以来,单例模式已经发生了很大的变化。 该模式的经典实现需要一种静态方式来访问实例,给出的示例:

 public class Singleton
 {
     public static Singleton Instance => ....

     public virtual void CallMe() { ... }
 }

但是,在编写测试时,这种方法有一个很大的缺点。 “Client”类将通过以下方式引用单例:

public class Client
{
    public void DoSomething()
    {
         Singleton.Instance.CallMe();
    }
}

使用这种形式,不可能模拟 CallMe 方法的实现并为 DoSomething 方法编写单元测试。

要实现类的单例实例,应该将其交给 IoC 容器,如下所示:

 public class Singleton
 {
    //no static properties
    public virtual void CallMe() { ... }
  }

  public class Client
  {
     private readonly Singleton _singleton;
     public Client(Singleton singleton)
     {
        _singleton = singleton;
     }
     public void DoSomething() => _singleton.CallMe();
  }

  //where you declare your services
  builder.Services.AddSingleton<Singleton>();
  builder.Services.AddScoped<Client>();

关于c# - 正确的单例类实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73675684/

相关文章:

c# - 获取当前登录用户的文档文件夹路径

c# - Visual Studio 2010 编辑器意外自动更正

.net - 空对象模式值得吗?

C#静态构造函数设计问题——需要指定参数

c# - 对于 .Net Native C# 应用程序,无法通过 WACK 测试并避免 ILT005 错误

c++ - 指针、类项和范围

python - 是否真的有必要对比较相同的类进行哈希处理?

python - 在 Python 中从同一类中的另一个调用一个方法

Java 在 setter 上自动发送事件

C# json反序列化对象