One way to handle this, or at least to do the same thing you're talking about in the PHP, is reflection. You can obtain a Class
object from a string specifying the fully-qualified class name, and use that class to create a new instance of itself dynamically.
public EditPart createEditPart(String name) throws [lots of stuff] {
return Class.forName(name).asSubclass(EditPart.class).newInstance();
}
However, this is a relatively inefficient way to use Java, and I wouldn't necessarily recommend it. Some other languages use reflection quite liberally (like PHP), but not so much with Java. Amber's factory idea is a good one and if I were doing it, I might go with that.
If you want to create your EditPart
based on the class of the model
object (as in your code sample), rather than on the name of the EditPart
subclass, then you can't use reflection. Well, you can, but you'll still need some way to tell the program which EditPart
corresponds to which type of model. One option would be to change the type of the model
parameter from Object
to some interface, say EditModel
, which you would write to have a method that returns an instance of the appropriate part. Like so:
public interface EditModel {
public EditPart getEditPart();
}
Then you could just write your createEditPart
as
public EditPart createEditPart(EditModel model) {
return model.getEditPart();
}
(actually, if it's that simple you probably don't even need createEditPart
at all). If you don't want to or can't do that, you could set up something with reflection that chooses the part class dynamically based on the name of the model class, but that really sounds unnecessarily complicated. At that point you'd definitely be better off going with the factory pattern.