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?
2 に答える
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.
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?