Note that there are some explanatory texts on larger screens.

plurals
  1. POOnly allow Factory method to instantiate objects (prevent instantiation of base class AND uninitialized objects)
    text
    copied!<p>I have a base class for handling "jobs". A factory method creates derived "job handler" objects according to job type and ensures the job handler objects are initialized with all the job information.</p> <p><strong>Calling factory method to request a handler for Job and Person assigned:</strong></p> <pre><code>public enum Job { Clean, Cook, CookChicken }; // List of jobs. static void Main(string[] args) { HandlerBase handler; handler = HandlerBase.CreateJobHandler(Job.Cook, "Bob"); handler.DoJob(); handler = HandlerBase.CreateJobHandler(Job.Clean, "Alice"); handler.DoJob(); handler = HandlerBase.CreateJobHandler(Job.CookChicken, "Sue"); handler.DoJob(); } </code></pre> <p><strong>The Result:</strong></p> <pre><code>Bob is cooking. Alice is cleaning. Sue is cooking. Sue is cooking chicken. </code></pre> <p><strong>Job handler classes:</strong></p> <pre><code>public class CleanHandler : HandlerBase { protected CleanHandler(HandlerBase handler) : base(handler) { } public override void DoJob() { Console.WriteLine("{0} is cleaning.", Person); } } public class CookHandler : HandlerBase { protected CookHandler(HandlerBase handler) : base(handler) { } public override void DoJob() { Console.WriteLine("{0} is cooking.", Person); } } </code></pre> <p><strong>A sub-classed Job Handler:</strong></p> <pre><code>public class CookChickenHandler : CookHandler { protected CookChickenHandler(HandlerBase handler) : base(handler) { } public override void DoJob() { base.DoJob(); Console.WriteLine("{0} is cooking chicken.", Person); } } </code></pre> <p><strong>The best way of doing things? I have struggled with these issues:</strong></p> <ol> <li>Ensure that all derived objects have a fully initialized base object (Person assigned).</li> <li>Prevent instantiation of ANY objects other than through my factory method that performs all the initialization.</li> <li>Prevent instantiation of the base class object.</li> </ol> <h1>The Job handler <code>HandlerBase</code> base class:</h1> <ol> <li>A <code>Dictionary&lt;Job,Type&gt;</code> maps Jobs to Handler classes.</li> <li>PRIVATE setter for job data (i.e., Person) prevents access except by factory method.</li> <li>NO default constructor and PRIVATE constructor prevents construction except by factory method.</li> <li>A protected "copy constructor" is the only non-private constructor. One must have an instantiated HandlerBase to create a new object, and only the base class factory can create a base HandlerBase object. The "copy constructor" throws an exception if one attempts to create new objects from a non-base object (again, preventing construction except by the factory method).</li> </ol> <p>A look at the base class:</p> <pre><code>public class HandlerBase { // Dictionary maps Job to proper HandlerBase type. private static Dictionary&lt;Job, Type&gt; registeredHandlers = new Dictionary&lt;Job, Type&gt;() { { Job.Clean, typeof(CleanHandler) }, { Job.Cook, typeof(CookHandler) }, { Job.CookChicken, typeof(CookChickenHandler) } }; // Person assigned to job. PRIVATE setter only accessible to factory method. public string Person { get; private set; } // PRIVATE constructor for data initialization only accessible to factory method. private HandlerBase(string name) { this.Person = name; } // Non-private "copy constructor" REQUIRES an initialized base object. // Only the factory method can make a HandlerBase object. protected HandlerBase(HandlerBase handler) { // Prevent creating new objects from non-base objects. if (handler.GetType() != typeof(HandlerBase)) throw new ArgumentException("THAT'S ILLEGAL, PAL!"); this.Person = handler.Person; // peform "copy" } // FACTORY METHOD. public static HandlerBase CreateJobHandler(Job job, string name) { // Look up job handler in dictionary. Type handlerType = registeredHandlers[job]; // Create "seed" base object to enable calling derived constructor. HandlerBase seed = new HandlerBase(name); object[] args = new object[] { seed }; BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; HandlerBase newInstance = (HandlerBase)Activator .CreateInstance(handlerType, flags, null, args, null); return newInstance; } public virtual void DoJob() { throw new NotImplementedException(); } } </code></pre> <p><strong>A look at the Factory Method:</strong></p> <p>Because I have made public construction of a new object impossible without already having an instantiated base object, the factory method first constructs a <code>HandlerBase</code> instance as a "seed" for calling the needed derived class "copy constructor".</p> <p>The factory method uses <code>Activator.CreateInstance()</code> to instantiate new objects. Activator.CreateInstance() looks for a constructor that matches the requested signature:</p> <p>The desired constructor is <code>DerivedHandler(HandlerBase handler)</code>, thus,</p> <ol> <li>My "seed" <code>HandlerBase</code> object is placed in <code>object[] args</code>.</li> <li>I combine <code>BindingFlags.Instance</code> and <code>BindingFlags.NonPublic</code> so that CreateInstance() searches for a non-public constructor (add <code>BindingFlags.Public</code> to find a public constructor).</li> <li>Activator.CreateInstance() instantiates the new object which is returned.</li> </ol> <h1>What I don't like...</h1> <p>Constructors are not enforced when implementing an interface or class. The constructor code in the derived classes is mandatory:</p> <pre><code>protected DerivedJobHandler(HandlerBase handler) : base(handler) { } </code></pre> <p>Yet, if the constructor is left out you don't get a friendly compiler error telling you the exact method signature needed: "'DerivedJobHandler' does not contain a constructor that takes 0 arguments".</p> <p>It is also possible to write a constructor that eliminates any compiler error, instead--WORSE!--resulting in a run-time error:</p> <pre><code>protected DerivedJobHandler() : base(null) { } </code></pre> <p>I do not like that there is no means of enforcing a required constructor in derived class implementations.</p>
 

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