Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to use Composition instead of Inheritance?
    primarykey
    data
    text
    <p>I have a <code>Configurator</code> class that, in order to do its work, must receive a <code>Context</code> object via an interface:</p> <pre><code>public class Configurator : IContextAware { private IContext _context; //property setter defined by the IContextAware interface public IContext Context { set { _context = value; } } // use _context object in other methods here ... } </code></pre> <p>I plan to write MANY <code>Configurator</code> types, which will all need to initalize their <code>_context</code> fields the same way. My first thought was "Why not anger every programmer on the Internet and use inheritance"?</p> <pre><code>public class ContextInitializer: IContextAware { // field to hold the injected context protected IContext _context; //property setter defined by the IContextAware interface public IContext Context { set { _context = value; } } } public class Configurator : ContextInitializer { // use _context object here ... } </code></pre> <p>This way, any other classes I write that need a Context object can just inherit from ContextInitializer, and use the Context object straight away.</p> <p>Pros: guaranteed consistent initialization, no distracting, duplicated initialize code in every class</p> <p>Cons: Implementation inheritance is evil!,.. um, Configurator cannot inherit from any other class.. ??</p> <p>I should clarify that one way or another, Configurator MUST implement the <code>IContextAware</code> interface. ALSO, the class must have a default/no-arg constructor, so constructor dependency injection is not an option here.</p> <p>Can someone suggest how Composition can be used to achieve the same benefits, but with more flexible design, and/or describe the real short-comings of the Inheritance solution above? Thanks!</p> <p>P.S. This is adapted from Spring.Net CodeConfig, if anyone is curious.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload