【发布时间】:2010-09-01 14:35:36
【问题描述】:
我创建了一个类,它允许访问对变量的全局访问,同时只创建一次,本质上是一个单例。
但是,它与实现单例的任何“正确”方法都不匹配。我认为它没有被提及,因为它有一些“错误”,但除了缺乏延迟初始化之外,我看不出它有任何问题。
有什么想法吗?
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();
}
}
【问题讨论】:
标签: c# design-patterns singleton