避免循环参考

时间:2011-12-07 14:19:06

标签: oop reference cycle

我有一个班级Form,其中包含Question项的哈希值。

class Form
{
    Dictionary < int , Answer> listOfQuestions;
}

class Question
{
    int questionId = 2;
    int dependsOnQuestion = 1;
    string answer;
    public bool IsDependancyMet() {/*problem*/}
}

我希望单个问题依赖于另一个问题的答案,例如,如果问题1的答案是“已婚”,则显示问题2,否则,不显示问题。

实施该方法的正确方法是什么?

是否会在问题实例中添加Form实例的引用,让后者访问问题的哈希。虽然我不喜欢它。

另一种方法是向Form类添加一个方法,该方法接收一个问题ID并检查是否满足所有它的依赖关系,但同样,问题应该知道表单实例。

在底线: 谁应该检查依赖关系以及如何使系统模块化,每个类尽可能少地了解它的环境?或者至少避免循环引用。

提前致谢。

1 个答案:

答案 0 :(得分:0)

的内容如何?
class Form
{
    Dictionary < int , Answer> listOfQuestions;
    int firstQuestion;

    public void NextQuestion() {
       // ... cycle through `listOfQuestions` looking for a question
       // whose dependencies are fullfilled and ask it.
    }
}

class Question
{
    // ...
    public List<int> GetDependencies();
    public void Ask();
    // ...
}

Form跟踪全局“提问”状态,而个别问题仅了解其直接依赖性。对我来说,这似乎是一种相对干净的方法。

相关问题