我有一个设计问题:
- 问题类:有一个问题和答案(字符串)
- TextQuestion 类:普通文本问答
- NumberQuestion 类:问题(字符串)、答案(数字 - 整数、浮点数...),并使用 epsilon 值检查答案
但我对 NumberQuestion 有疑问。我必须选择正确的答案,将其转换为数字,并与用户的答案进行比较。那么我怎样才能得到答案呢?使用 getter 方法并不安全。还是我的设计不好?我该如何改变?
public abstract class Question { private String question; private String answer; public Question(String question, String answer) { this.question = question; this.answer = answer; } public boolean checkAnswer(String yourAnswer) { // default implementation } } class TextQuestion extends Question { // Answer and Question is always string type, it's OK, not problem } class NumberQuestion extends Question { // Question is String, OK // Answer: input is number, accept approximately // Ex: Question: 1/3 = ? // Answer: 0.3 or 0.33 or 0.333 are accepted (using an Epsilon value) // so must override checkAnswer public boolean checkAnswer(String yourAnswer) { // HOW can I do? } }