【问题标题】:Direct component object直接组件对象
【发布时间】:2018-01-10 09:33:44
【问题描述】:

我不明白短语直接组件对象Law of Demeter's article 的上下文中是什么意思。正如我所见,该术语取自David Block's article。那么,这个术语是什么?我在哪里可以获得真实的例子和更多关于它的信息?

【问题讨论】:

  • 自己的字段/属性。 this.field.method() - 好的,this.field.anotherField.method() - 不好。
  • 你确定吗?让我们看看case 1:方法m可能只调用O本身的方法。在我看来,您的示例与规则相矛盾。此外,还有一个只使用一个点的规则
  • 顺便说一句,在 wiki 中,他们“隐藏”了一个点。 a.b.Method()this.a.b.Method(),如果使用更正式的样式。

标签: oop coupling law-of-demeter


【解决方案1】:

直接组件对象在这种情况下是类的成员变量。例如:

class MyClass
{
    IService service;

    public MyClass(IService service)
    {
        this.service = service;
    }

    public void MyMethod(Param param)
    {
        // O itself
        this.AnotherMethod();

        // m's parameters
        param.Method1();

        // Any objects created/instantiated within m
        TempObject temp = new TempObject();
        temp.DoSomething();

        // O's direct component objects
        service.ProvideService();

        // violates Law of Demeter
        service.GetConfig().Update();
    }

    private void AnotherMethod()
    {
        ...
    }
}

此示例显示了被认为符合得墨忒耳法则的各种方法调用。在这种情况下,成员变量service 是一个直接的组件对象。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-09
    • 2011-06-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多