问题
I am learning Singleton design pattern in C#, and I have written below code in two ways, and I want to know Which one is the right way to create a Singleton class:
public sealed class TranslationHelper
{
// first way
private static readonly TranslationHelper translationHelper = new TranslationHelper();
// second way
public static readonly TranslationHelper translationHelpers = new TranslationHelper(); // Direct call
public static TranslationHelper GetTranslationHelper()
{
return translationHelper;
}
private TranslationHelper()
{
}
}
CALL:
TranslationHelper instance = TranslationHelper.GetTranslationHelper();
TranslationHelper ins = TranslationHelper.translationHelpers;
I am beginner so I am not sure if both methods are same. Please guide me.
回答1:
If you are using .Net 4 or higher you can use the Lazy<T>
type like this:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy =
new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance { get { return lazy.Value; } }
private Singleton()
{
}
}
By using this design pattern with a private constructor you are insuring that the class and it is only created at the time it is used. This is ensured because
- It can only be called by itself so it does not get instantiated ahead of time.
- The
Lazy<T>
keyword when used with theprivate static readonly
lambda function now provides a visually clear way of lazily creating an instance of the class from within the function itself. - The
public Singleton Instance
property provides a way to access that singleton from outside the class.
来源:https://stackoverflow.com/questions/52173966/whats-the-correct-way-to-have-singleton-class-in-c-sharp