【问题标题】:Is this a cyclic dependency这是一个循环依赖吗
【发布时间】:2018-09-30 04:35:12
【问题描述】:
class foo{
Bar b;
}

class bar{
Class clazz = foo.class;
}

上面的 sn-p 是否显示了循环依赖。类 foo 具有 bar 类对象的引用。类 bar 引用了 foo 类本身。

【问题讨论】:

    标签: design-patterns object-oriented-analysis cyclic-dependency


    【解决方案1】:

    虽然具体情况可能会因您使用的语言而略有不同,但在更纯粹的面向对象术语中,不会。

    查看受 Smalltalk 启发的语言(如 Ruby)会有所帮助,以了解情况如何:

    class Foo
        def initialize()
            @b = Bar.new()
        end
        def what_is_b() # instance method can call class method who
            @b.who()
        end
        def who()
            "foo instance"
        end
        def self.who() # class method can't call instance method what_is_b
            "foo class"
        end
    end
    
    class Bar
        def initialize()
            @clazz = Foo
        end
        def what_is_clazz()
            @clazz.who()
        end
        def who()
            "bar instance"
        end
        def self.who()
            "bar class"
        end
    end
    
    f = Foo.new()
    puts f.who()
    puts f.what_is_b()
    
    puts " and "
    
    b = Bar.new()
    puts b.who()
    puts b.what_is_clazz()
    

    这个输出:

    foo instance
    bar instance
     and 
    bar instance
    foo class
    

    这表明foo instance 具有-a bar instance,而bar instance 具有-a foo class。在纯 OO 中,foo classfoo instances 的工厂,并且类方法不能引用实例方法,但反之亦然,所以 foo instances 可以依赖于 foo class,但不能反过来。

    所以在这个人为的例子中,foo instance 是依赖树的头部,而foo class 是尾部。如果不是在 clazz 实例变量中引用 Foo 类,而是引用了 foo instance,那么您将拥有一个循环依赖图

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-17
      • 1970-01-01
      • 1970-01-01
      • 2011-09-27
      • 1970-01-01
      相关资源
      最近更新 更多