我创造的这个单身人士怎么了?

Joh*_*ohn 4 c# singleton design-patterns

我创建了一个类,它允许访问变量的全局访问,同时只创建一次,基本上是一个单例.

但是,它与实现单例的任何"正确"方法都不匹配.我假设它没有被提及,因为它有一些'错误',但除了懒惰的初始化之外,我看不出任何问题.

有什么想法吗?

static class DefaultFields
{
    private static readonly string IniPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "defaultFields.ini");
    private static readonly IniConfigSource Ini = GetIni();               

    /// <summary>
    /// Creates a reference to the ini file on startup
    /// </summary>
    private static IniConfigSource GetIni()
    {
        // Create Ini File if it does not exist
        if (!File.Exists(IniPath))
        {
            using (FileStream stream = new FileStream(IniPath, FileMode.CreateNew))
            {
                var iniConfig = new IniConfigSource(stream);
                iniConfig.AddConfig("default");
                iniConfig.Save(IniPath);
            }
        }

        var source = new IniConfigSource(IniPath);
        return source;
    }

    public static IConfig Get()
    {
        return Ini.Configs["default"];
    }

    public static void Remove(string key)
    {
        Get().Remove(key);
        Ini.Save();
    }

    public static void Set(string key, string value)
    {
        Get().Set(key, value ?? "");
        Ini.Save();
    }
}
Run Code Online (Sandbox Code Playgroud)

Tri*_*tan 5

它不遵循通常的单例模式,因为您的类是静态的,只是控制对静态变量的访问.

作为单例的通常是类的静态单个实例,其中唯一的静态函数是创建和访问将变量存储为普通非静态成员变量的单例.

意思是这个类可以很容易地被改变或者被设置为多一次,但是你的不能