简体   繁体   中英

How to extract a superclass to encapsulate common code?

I have an application which uses plugins. After creating several of them I've found that a big chunk of code is repeated here and there on them so I want to extract a super "plugin base".

Previous the refactor I had the following structure:

先前的结构

After the refactor I have the next one:

当前结构

I currently don't find a way to model the fact that the plugin engine has a property settings of type plugin settings and the plugin engine base has a property settings of type plugin settings base . I feel that somehow should be a way to declare that the settings property of the plugin engine base should be a "cast" of the settings property of the plugin engine and to model the fact that they both are the same property.

I'm not sure if the problem is explained enough. Feel free to ask for clarifications.

Thanks.

You can use generics. Create generic base class and specify generic parameter constraint to be of type PluginSettingsBase .

abstract class PluginEngineBase<T>
   where T: PluginSettingsBase
{
   public abstract T Settings { get; set; }
}

Inherit from base class parametrized by PluginsSettings class (thus it is inherited from PluginSettingsBase )

class PluginEngine : PluginEngineBase<PluginsSettings>
{
   public PluginSettings Settings { get; set; }
}

Same with PluginData .

An approach I found:

Base class:

class PluginEngineBase
{
    public PluginSettingsBase Settings { get; set; }
}

Inheritor:

class PluginEngine : PluginEngineBase
{
    public PluginSettings Settings
    {
        get
        {
            return (PluginSettings)base.Settings;
        }
        set
        {
            base.Settings = value;
        }
    }
}

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