使用这种模式有什么好处或原因?
public sealed class myStaticClass { private static bool _initialized; private static object _lockObject; private static string _someStaticField; private static int _anotherStaticField; private static string _nthStaticField; static myStaticClass() { _initialized = false; _lockObject = new object(); } public myStaticClass() { } public static void Initialize() { if(!_initialized) { lock(_lockObject) { if(!_initialized) { //do initializing _someStaticField = someApplicationSetting; _anotherStaticField = anotherApplicationSetting; _nthStaticField = nthApplicationSetting; _initialized = true; } } } } public static string NthStaticField { get { Initialize(); return _nthOtherField; } } }
如果静态构造函数被保证在任何类成员被访问之前被调用并且它只被调用一次那么为什么不将所有初始化逻辑放在静态构造函数中?
编辑:我已经更新了模式,以更好地反映我发现它的.net框架中的类.我已经将类上的static修饰符更改为sealed,我还添加了一个空的公共构造函数.
PS.如果您想知道,我见过这种模式的类是FormsAuthentication类.