如何在对象层次结构中找到周期? [英] How do I find cycles in my object hierarchy?

查看:97
本文介绍了如何在对象层次结构中找到周期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个 Company 类,它引用了另一个 Company 实例来表示父级。可以说有四个公司 c1 c2 c3 & c4 c2 c3 c4 将母公司设置为 c1

There is a class Company, which has reference to another instance of Company to represent the parent. Lets say there are four companies c1, c2, c3 & c4 and c2, c3, c4 has parent company set as c1.

例如:

public class Company {
  public Company parent;

  public Company() { }
  public Company(Company parent) {
    this.parent = parent;
  }

  public static void main(String[] args) {
    Company c1 = new Company();
    Company c2 = new Company(c1);
    Company c3 = new Company(c1);
    Company c4 = new Company(c1);
}

如果我们设置 c2 作为 c1 的母公司:

If we set c2 as parent company of the c1:

c1.parent = c2;

然后将创建一个 循环复杂度 公司层次结构中的无限循环,我们必须在系统中避免这种情况。

then it will create a Cyclomatic Complexity infinite loop in the company hierarchy, which we have to avoid in our system.

希望能够在运行时检测到这一点。在上述情况下,检查同一类对象的圈复杂度的最佳算法是什么?

We would like to be able to detect this in runtime. What is the best algorithm to check the cyclomatic complexity in objects of the same class in the above situation?

推荐答案

您的任务没有任何内容与圈复杂度有关。您的实体基本上形成一个图,并且您想检测其中的循环。常用的方法是执行 DFS

Your task has nothing to do with cyclomatic complexity. Your entities basically form a graph and you want to detect cycle in it. The common way to do that is to perform a DFS.

您可以找到很多示例操作方法通过互联网

You can find plenty of examples how to do that over the internet.

这篇关于如何在对象层次结构中找到周期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆