C#Singleton设计模式基础



最近刚开始尝试学习一些设计模式。目前正在尝试让我的singleton返回一个新对象。然而,它不断抛出错误"无法将方法组"getInstance"转换为非委托类型"MainWdinow.CustomerLoader"。您打算调用该方法吗?

这是设计模式方法的代码

public class CustomerLoader
{
private static Customer firstInstance = null;
public static Customer getInstance()
{
if(firstInstance ==null)
{
firstInstance = new Customer();
}
return firstInstance;
}
}

这是我尝试调用方法的地方,我得到了上面提到的错误

CustomerLoader t = CustomerLoader.getInstance();

我希望我的singleton完成下面代码的工作,并创建客户对象的新实例

Customer T = new Customer;

使用这个。与版本不同,它也是线程安全的

private static readonly Lazy<Customer> _instance = new Lazy<Customer>(() => new Customer());
public static Customer Instance => _instance.Value;

但是您应该真正使用依赖项注入而不是singleton。

您的命名已关闭,看起来像Java,请检查https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/names-of-type-members

私人会员不在指南范围内。但即使是微软也将_camelCase用于corefx中的私有字段https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/coding-style.md

使用此示例:

public class Singleton    
{
private static Singleton instance = null;
private static readonly object padlock = new object();
Singleton()
{
}
public static Singleton Instance
{
get
{
lock (padlock)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}
}
  1. 辛格尔顿应该是一个班,而不是三个班
  2. 小心使用它,因为您的实现不是线程安全的。请在此处查看此挂锁变量。它可以防止在多线程应用程序中创建多个实例
CustomerLoader.getInstance

是一个函数,无法将其分配给客户加载器

你的代码应该更像这样:

class Train
{
protected Train() { }
protected static Train instance;
public static Train GetSingeltonInstance()
{
if(instance == null)
{
instance = new Train();
}
return instance;
}
}
class TainUser
{
private readonly Train train;
public TainUser()
{
train = Train.GetSingeltonInstance();
}
}

最新更新