augment the factory pattern in java

前端 未结 3 842
Happy的楠姐
Happy的楠姐 2021-02-04 19:48

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

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-04 20:27

    One possibility:

    public enum QuestionType {
        TrueFalse(TrueFalseQuestion.class),
        MultipleChoice(MultipleChoiceQuestion.class),
        Essay(EssayQuestion.class)
    
        private final Class implementationType;
        QuestionType(Class 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();
    }
    

提交回复
热议问题