I am trying to use a factory pattern to create a QuestionTypeFactory where the instantiated classes will be like MultipleChoice, TrueFalseQuestion etc.
The factory code
One possibility:
public enum QuestionType {
TrueFalse(TrueFalseQuestion.class),
MultipleChoice(MultipleChoiceQuestion.class),
Essay(EssayQuestion.class)
private final Class extends Question> implementationType;
QuestionType(Class extends Question> implementationType) {
this.implementationType = implementationType;
}
public Question createQuestion() {
return implementationType.newInstance();
}
}
Of course, this gets rid of the factory and assumes all your questions have no-args constructors, but as far as I can tell, it covers all the cases of the code sketch above. If construction for the particularly classes is more complicated, you can always setup something like:
public enum QuestionType {
TrueFalse { public Question createQuestion() { /* construction logic goes here */ } }
public abstract Question createQuestion();
}