Home > Enterprise >  Parent class for singleton pattern | setting field to instance of child class
Parent class for singleton pattern | setting field to instance of child class

Time:08-22

I’m trying to implement a simple singleton parent class for internal use (I only want to avoid static fields and don’t care about safety).

The reason I want a generic parent class is so I don’t have to worry about boilerplate and can simply inherit from Simpleton. I plan on having quite a few of these.

Here’s what I have:

class Simpleton
{
    static Simpleton instance;
    static Simpleton()
    {
        instance = new Simpleton();
    }
    
    // I know this naming isn’t ideal, but I’m going for brevity and I’m the only one using this codebase
    static Simpleton I { get => instance; }

}

This works if I actually want to use an instance of Simpleton but I want to create a child class and use it:

class Settings : Simpleton
{
    public int testSetting = 1;
}

// somewhere else
void Test()
{
    // compiler error since Simpleton does not contain the field `testSetting`
    var num = Settings.I.testSetting;
}

I just want to make the static Simpleton() function set instance to an instance of the child class. I can do this with reflection, but I can’t figure out how to do it such that the compiler knows that it is an instance of the child class.

I’m surprisingly stumped on how to make this work, and since my main goal is to have as little boilerplate as possible in the child class, I want to avoid overriding to whatever extent possible.

CodePudding user response:

Make your Singleton a generic, and then derive Settings from Singleton<Settings>, like this:

var t = Settings.Instance.testSetting;

Console.WriteLine(t);

class Singleton<T> where T: new()
{ 
    public static T Instance = new T();
}

class Settings : Singleton<Settings>
{
    public int testSetting = 1;
}
  • Related