我创建了一个类,它允许访问全局变量,而只创建一次,实质上是一个单例。我创建的这个单例有什么问题
但是,它不符合任何'正确'的方式来实现一个单身人士。我认为它没有提到,因为它有一些'错误',但我不能看到任何问题,除了缺乏延迟初始化。
有什么想法?
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();
}
}
参考http://stackoverflow.com/questions/3532161/what-is-the-difference-between-a-singleton-pattern-and-a-static-class-in-java – Numenor 2010-09-01 14:50:59