简体   繁体   中英

Derived class should always be singleton

I am trying to create a base class with some functionality shared between all derived classes. And all derived classes should be Singletons. Below a pseudo example.

class ExtensionSettings
{
    public string GetConfigHtml()
    {
        // creat conifig html for all properties
    }

    public void SaveSettings()
    {
        // save stuff
    }
}

class SettingsA : ExtensionSettings
{
    private static SettingsA instance;
    public static SettingsA Instance {get {return instance ?? (instance = new SettingsA());}}

    public string setting1{get;set;}
    public string setting2{get;set;}
}

class SettingsB : ExtensionSettings
{
    private static SettingsB instance;
    public static SettingsB Instance {get {return instance ?? (instance = new SettingsB());}}

    public string setting1{get;set;}
    public string setting2{get;set;}
}


static void Main(string[] args)
{
    System.Console.WriteLine(SettingsA.Instance.setting1);
    System.Console.WriteLine(SettingsB.Instance.setting2);
}

Is it possible to move the instancing part to the ExtensionSettings base class?

base class doesn't know about the rest of the object to be instantiated. basically, when you derive from a base class, the extra logic added in derived class is hidden from base class. therefore, doing instantiation in the base class is not possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM