我創建了一個類,它允許訪問全局變量,而只創建一次,實質上是一個單例。我創建的這個單例有什麼問題
但是,它不符合任何'正確'的方式來實現一個單身人士。我認爲它沒有提到,因爲它有一些'錯誤',但我不能看到任何問題,除了缺乏延遲初始化。
有什麼想法?
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