C#Singleton设计模式基础

时间:2018-12-07 10:43:51

标签: c# design-patterns 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();

我希望我的单身人士完成下面的代码,并创建客户对象的新实例

Customer T = new Customer;

3 个答案:

答案 0 :(得分:2)

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

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

但是您应该真正使用依赖注入代替单例。

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

私人成员不受指南的保护。但即使是Microsoft,也将_camelCase用于corefx https://github.com/dotnet/corefx/blob/master/Documentation/coding-guidelines/coding-style.md

中的私有字段

答案 1 :(得分:0)

使用此示例:

if unitid >= 70000:
elif  unitid >= 60000:
  1. 单人应该是一堂课,而不是三堂课。
  2. 请小心使用它,因为您的实现不是线程安全的。请在此处查看此挂锁变量。这样可以防止在多线程应用程序中创建多个实例。

答案 2 :(得分:-1)

CustomerLoader.getInstance

是一个功能,您不能将其分配给     CustomerLoader

您的代码应更像这样:

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();
    }
}