Мне нужен синглтон, который:
Я использую .NET 3.5.
Я начал с реализации Джона Скита (5-я версия), используя статический подкласс:
public sealed class Singleton
{
IEnumerable Values {get; private set;}
private Singleton()
{
Values = new[]{"quick", "brown", "fox"};
}
public static Singleton Instance { get { return Nested.instance; } }
private class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
] Это ставит галочки почти во всех полях, кроме «инициализации триггера извне». Поскольку фактическая инициализация происходит внутри ctor, это не может происходить более одного раза.
Как это можно сделать?
Синглтон будет использоваться следующим образом:
public static void Main(){
//do stuff, singleton should not yet be initialized.
//the time comes to initialize the singleton, e.g. a database connection is available
//this may be called 0 or more times, possibly on different threads
Singleton.Initialize();
Singleton.Initialize();
Singleton.Initialize();
//actual call to get retrieved values, should work
var retrieveVals = Singleton.Instance.Values;
}