2

我正在为问卷创建一个框架。

问卷有几个问题。我的情况是寻找一个名为 的类Question,它支持您想要的任何答案。

我的意思是,有些问题只需要一个答案,另一些问题需要两个答案,其他问题需要字符串、整数、双精度或开发人员构建的任何新结构(例如,想象开发人员正在创建一个使用 Fraction 结构作为答案的数学问题)。

换句话说,我需要支持任何数据类型或数量的答案。

所以我正在考虑创建一个名为 的抽象类Question,其中将包含一个Dictionary响应。

public abstract class Question
{
    protected Question(string questionText)
    {
        this.QuestionText = questionText;
        this.Responses = new Dictionary<string, object>();
    }

    public string QuestionText
    {
        get;
        set;
    }

    public IDictionary<string, object> Responses { get; protected set; }
}

例如,如果我创建一个新的Question,这将是演示。

public sealed class Question1 : Question
{
    public Question1(string questionText)
        : base(questionText)
    {
    }

    public int? Response1
    {
        get
        {
            int? value = null;

            if (this.Responses.ContainsKey("Response1"))
                value = this.Responses["Response1"] as int?;

            return value;
        }
        set
        {
            this.Responses["Response1"] = value;
        }
    }
}

你怎么看这个想法?我的第一个疑问:我将答案包含在班级而不是另一个独立班级中是否正确。

4

3 回答 3

2

谁来回答这些问题?让我们假设人们。鉴于此,一个人可能会以某种方式登录或识别自己。这让我认为Person 模型应该包含 Responses,并引用每个问题。

// pseudocode 
class Person 
   int PersonID 
   IList Responses     

class Response
   int ResponseID
   int QuestionID 
   string ResponseValue 

class Question
   int QuestionID
   string QuestionText 
   IList AllowedResponses 
   bool AllowsMultipleResponses
于 2012-06-26T17:41:47.470 回答
1

我将从 jcollum 的模型开始,但我会做一些不同的事情,并在使用对象时添加泛型。

// pseudocode 
class Person 
   int PersonID 
   IEnumerable<IQuestionResponse> QuestionResponses

//non generic interface to allow all QuestionRespones 
//to be stored in one typed collection
interface IQuestionResponse

class QuestionResponse<TResponse> : IQuestionResponse
   Question<TResponse> Question
   IEnumerable<TResponse> Responses

class Question<TResponse>
   string QuestionText 
   IEnumerable<TResponse> AllowedResponses 
   bool AllowsMultipleResponses
于 2012-06-26T18:18:42.620 回答
0

如果您在问题中包含回复,您将违反单一责任原则。换句话说,如果例如您决定更改响应映射到问题的方式,为什么要更改 Question 类。还缺少一个响应类。此外,使用问题和响应列表创建一个 QuestionResponsesMapping 类。

要回答您在评论中发布的问题(java 中的语法):

这个 QuestionResponsesMapping 可以有一个键为 Question 和 value 的映射

List<Response<T extends Object & SomeInterface>>

. 确保为 Question 和 Response 类实现 hashCode() 和 equals()。通过实现 Response as 来满足您能够为响应存储任何类型的数据类型的要求Response<T extends Object & SomeInterface>>。这里的 SomeInterface 可以具有跨数据类型通用的方法。

于 2012-06-26T18:18:31.957 回答