Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6136301
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T17:35:11+00:00 2026-05-23T17:35:11+00:00

I have a base class for handling "jobs". A factory method creates derived "job

  • 0

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.

Calling factory method to request a handler for Job and Person assigned:

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();
  }

The Result:

Bob is cooking.
Alice is cleaning.
Sue is cooking.
Sue is cooking chicken.

Job handler classes:

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);
  }
}

A sub-classed Job Handler:

public class CookChickenHandler : CookHandler
{
  protected CookChickenHandler(HandlerBase handler) : base(handler) { }
  public override void DoJob()
  {
    base.DoJob();
    Console.WriteLine("{0} is cooking chicken.", Person);
  }
}

The best way of doing things? I have struggled with these issues:

  1. Ensure that all derived objects have a fully initialized base object (Person assigned).
  2. Prevent instantiation of ANY objects other than through my factory method that performs all the initialization.
  3. Prevent instantiation of the base class object.

The Job handler HandlerBase base class:

  1. A Dictionary<Job,Type> maps Jobs to Handler classes.
  2. PRIVATE setter for job data (i.e., Person) prevents access except by factory method.
  3. NO default constructor and PRIVATE constructor prevents construction except by factory method.
  4. 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).

A look at the base class:

public class HandlerBase
{
  // Dictionary maps Job to proper HandlerBase type.
  private static Dictionary<Job, Type> registeredHandlers =
    new Dictionary<Job, Type>() {
      { 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(); }
}

A look at the Factory Method:

Because I have made public construction of a new object impossible without already having an instantiated base object, the factory method first constructs a HandlerBase instance as a "seed" for calling the needed derived class "copy constructor".

The factory method uses Activator.CreateInstance() to instantiate new objects. Activator.CreateInstance() looks for a constructor that matches the requested signature:

The desired constructor is DerivedHandler(HandlerBase handler), thus,

  1. My "seed" HandlerBase object is placed in object[] args.
  2. I combine BindingFlags.Instance and BindingFlags.NonPublic so that CreateInstance() searches for a non-public constructor (add BindingFlags.Public to find a public constructor).
  3. Activator.CreateInstance() instantiates the new object which is returned.

What I don’t like…

Constructors are not enforced when implementing an interface or class. The constructor code in the derived classes is mandatory:

protected DerivedJobHandler(HandlerBase handler) : base(handler) { }

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".

It is also possible to write a constructor that eliminates any compiler error, instead–WORSE!–resulting in a run-time error:

protected DerivedJobHandler() : base(null) { }

I do not like that there is no means of enforcing a required constructor in derived class implementations.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T17:35:12+00:00Added an answer on May 23, 2026 at 5:35 pm

    I see three responsibilities in your HandlerBase that, if decoupled from one another, may simplify the design problem.

    1. Registration of handlers
    2. Construction of handlers
    3. DoJob

    One way of reorganizing this would be to put #1 and #2 on a factory class, and #3 on a class with an internal constructor so that only the factory class can call it per your internal requirements. You can pass in the Person and Job values directly rather than letting the constructor pull them from a different HandlerBase instance, which would make the code easier to understand.

    Once these responsibilities are separated, you can then more easily evolve them independently.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have base class BaseClass and derived classes DerivedA , DerivedB , and DerivedC
I have a base class A and a derived class B: class A {
I have multiple objects that inherit from a base class and am trying to
I have a generic method in a base class similar to the following: protected
I have an interface with several events I have base class implementing the interface
I have a base class, defined as below (I'm also using DevExpress components): public
I have a base class called Component. I also have 2 interfaces I2DComponent, and
I have a base class, B, which has two constructors, one with no paremeters
I have a base class where I derive several classes. I have another class
I have a base class for all my textboxes and I want to set

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.