Answer the question
In order to leave comments, you need to log in
Is the implementation of singleton inheritance correct?
Ku!
A small desktop application, there are a couple of dozen classes, the objects of which you don’t want to produce.
The first solution that comes to mind is to make them static, with all the ensuing consequences: all class fields are static, all methods are also static, which seems not very correct in an OOP language.
The second idea is to make everything singletons:
public class YellowClass
{
private static YellowClass _instance;
private YellowClass() { }
public static YellowClass GetInstance()
{
return _instance ?? (_instance = new YellowClass());
}
}
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
namespace DemoApplication
{
static class Program
{
static void Main(string[] args)
{
var yellowClass1 = new YellowClass();
var yellowClass2 = YellowClass.Instance;
Debug.Print(yellowClass1.Equals(yellowClass2) ? "All good!" : "WTF???");
}
}
public class Singleton<T>
{
[SuppressMessage("ReSharper", "InconsistentNaming")]
private static readonly Lazy<T> _instance = new Lazy<T>(CreateInstance);
private static T CreateInstance()
{
return (T)Activator.CreateInstance(typeof(T), true);
}
public static T Instance
{
get { return _instance.Value; }
}
}
public class YellowClass : Singleton<YellowClass>
{
}
}
Answer the question
In order to leave comments, you need to log in
In my opinion, garbage and nonsense. Discover dependency injection.
Well, in order not to impose additional restrictions on T (in this case, the presence of a non-parameterized constructor), you can write this: (T)Activator.CreateInstance(typeof(T), true);
I use this design, time-tested
public class Singleton<T> where T : class
{
private static readonly Lazy<T> _instance = new Lazy<T>(() => (T)typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, null, new Type[0], null).Invoke(null), true);
public static T Instance => _instance.Value;
}
public sealed class CustomSingleton : Singleton<CustomSingleton>
{
}
var single = CustomSingleton.Instance
The first solution that comes to mind is to make them static, with all the ensuing consequences: all class fields are static, all methods are also static, which seems not very correct in an OOP language.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question