djechlin
djechlin

Reputation: 60768

How to avoid lots of boilerplate in a polymorphic factory pattern

I have an abstract Command class. Every Command class created from a certain class, Fetcher, needs to be endowed with certain properties. Normally this looks like a factory pattern - Fetcher creates a CommandFactory that will prepare the Command when creating it. However there are about a dozen derived classes and I don't see how to do this without having a different concrete factory for each concrete class, or a different method createConcrete1Command that will have to be extended each time a new Command class is created. Is there any strategy for this?

Upvotes: 3

Views: 330

Answers (2)

djechlin
djechlin

Reputation: 60768

The solution I've found to this situation is as follows:

Constructor:

public BaseClass(Parameters p); // can be expanded and endowed as necessary; essentially anything a constructor can do can happen here.

All derived classes will of course taken a Parameters as an argument, however Parameters can be extended as necessary with no need to touch the constructor of any derived class.

Upvotes: 1

akuhn
akuhn

Reputation: 27793

You might try using Class.forName(String) and Class.newInstance to programmatically create new instances. Though generally, I find that the factory pattern always lends itself to boilerplate code in Java due to the lack of metaclasses.

So something like (module Exception handling and assuming that for each Foo class there is a FooCommand class)

 public class AbstractFoo {

     public ICommand createCommand() {
         return Class.forName(this.getClass()+"Command").newInstance();
     }

 }

and calling createCommand() on Fetcher extends AbstractFoo creates an instance of FetcherCommand.

Is that what you're looking for?

Upvotes: 0

Related Questions