我从单例类开始学习设计模式。您能解释一下以下实例属性实现之间的区别吗?
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/