如何设计问卷调查框架/对象模型?

时间:2012-06-26 17:31:44

标签: c# oop design-patterns

我正在建立问卷调查框架。

调查问卷有几个问题。我的情况是寻找一个名为Question的课程,它可以根据需要支持任何答案。

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

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

所以我在考虑创建一个名为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;
        }
    }
}

您如何看待这个想法?我的第一个疑问是:将答案纳入班级而不是另一个独立班级是否正确。

3 个答案:

答案 0 :(得分:1)

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

// 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

答案 1 :(得分: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

答案 2 :(得分:0)

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

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

此QuestionResponsesMapping可以有一个地图,其中键为问题,值为

List<Response<T extends Object & SomeInterface>>

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