I have a small hierarchy of classes that all implement a common interface.
Each of the concrete class needs to receive a settings structure containing for instance only public fields. The problem is that the setting structure
- has a part common to all classes
- has another part that vary from one concrete class to another
I was wondering if you had in your mind any elegant design to handle this. I would like to build something like:
BaseFunc doer = new ConcreteImplementation1();
with ConcreteImplementation1 implements BaseFunc. And have something like
doer.setSettings(settings)
but have the ”settings” object having a concrete implementation that would be suitable to ConcreteImplementation1.
How would you do that?
This may be a named design pattern, if it is, I don’t know the name.
Declare an abstract class that implements the desired interface. The abstract class constructor should take an instance of your settings object from which it will extract the global settings. Derive one or more classes from the abstract class. The derived class constructor should take an instance of your settings object, pass it to the parent class constructor, then extract any local settings.
Below is an example:
class AbstractThing implements DesiredInterface { private String globalSettingValue1; private String globalSettingValue2; protected AbstractThing(Settings settings) { globalSettingValue1 = settings.getGlobalSettingsValue1(); globalSettingValue2 = settings.getGlobalSettingsValue2(); } protected String getGlobalSettingValue1() { return globalSettingValue1; } protected String getGlobalSettingValue2() { return globalSettingValue2; } } class DerivedThing extends AbstractThing { private String derivedThingSettingValue1; private String derivedThingSettingValue2; public DerivedThing(Settings settings) { super(settings); derivedThingSettingValue1 = settings.getDerivedThingSettingsValue1(); derivedThingSettingValue2 = settings.getDerivedThingSettingsValue2(); } }