[英]Storing multiple strings in a class hierarchy designed to hold a single string
I have a hierarchy of classes. 我有一个类的层次结构。 Each class represent different kind of question in a survey.
在调查中,每个班级代表不同类型的问题。
Up until now, users can give a single answer to a question (via input box, ratio button or from a dropdown). 到目前为止,用户可以(通过输入框,比率按钮或从下拉菜单中)对一个问题给出单个答案。 The answer to each asked question is stored as a string in the
answer
field inherited from Question
. 每个问题的答案都作为字符串存储在从
Question
继承的answer
字段中。
I have been tasked with adding a MultiChoice question to the hierarchy. 我的任务是向层次结构添加一个MultiChoice问题。 A multi choise question enable users to provide multiple answers (such as by selecting multiple options in a group of checkboxes, or via multiple text boxes).
多选择题使用户能够提供多个答案(例如,通过在一组复选框中选择多个选项,或通过多个文本框)。
In the diagram below, the green class is the one I need to add. 在下图中,绿色类是我需要添加的类。 My problem is that the current structure assumes a single answer only.
我的问题是当前结构仅假设一个答案。
I've thought of two possible modifications: 我想到了两种可能的修改:
answer
field. answer
字段中。 list<String> answers
and adding an getter getAnswers()
to MultiChoice
. list<String> answers
,并向MultiChoice
添加一个getter getAnswers()
。 I see problems with both approaches. 我发现两种方法都存在问题。 The first one adds the responsability of parsing a possible csv of answers to the caller.
第一个增加了解析可能的csv答案给呼叫者的责任。 The second one violates the Liskov substitution principle.
第二个违反了Liskov替代原则。
My question is: How can I support multiple answers in MultiChoice
without introducing such problems? 我的问题是:如何在
MultiChoice
支持多个答案而不引入此类问题?
The simple answer is of course to change the interface to 简单的答案当然是将界面更改为
List<String> getAnswers();
void addAnswer(String answer);
But that's still a struct rather than object oriented design. 但这仍然是结构而不是面向对象的设计。 To me this rather feels like a case for a visitor pattern with just having a interface like
在我看来,这就像访问者模式的一种情况,只是具有一个类似
void accept(Visitor v);
and a vistor interface like 和一个vistor界面
interface Visitor<T> {
T visit(T arg, DropDown answer);
T visit(T arg, MultiChoice answer);
T visit(T arg, SingleChoice answer);
...
}
with a visit method per concrete answer type. 每个具体答案类型的访问方法。 And then implement each statistics on the answers as a implementation of Visitor if statistics is what you wanna do.
如果您想做的是统计,则将每个统计信息作为对访客的一种实现来实施答案。 However, always think in what you wanna do with the data, not in dump fields.
但是,请始终考虑要处理数据的内容,而不要考虑转储字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.