构图 vs 内在 类

Composition vs Inner Classes

合成和内部 classes 有什么区别和相似之处? 我正在尝试学习 Java 的原理并尝试弄清楚整个图像。对我来说最好是打个比方,看看概念之间的异同,才能正确使用。

组成的定义: "Composition is the design technique to implement has-a relationship in classes"。 "Java composition is achieved by using instance variables that refers to other objects"

内部定义class(或成员class,非匿名): "A member class is also defined as a member of an enclosing class, but is not declared with the static modifier. This type of inner class is analogous to an instance method or field. An instance of a member class is always associated with an instance of the enclosing class, and the code of a member class has access to all the fields and methods"

所以,通过对比这两个定义,我看到了一些相似之处:

1. Both have HAS-A relationship
2. Both are strictly dependent on the outer class lifetime
3. can be declared private

差异:

1. Inner classes uses classes, composition use instances (?!)
2. In composition no restriction to use the variables of the "outer" class

如果我完全错了请指正,我需要更好地追溯两个概念的界限。

你说得对,composition 和 inner-classes 都实现了 "has-a" 方案,但它们有很多不同。

组合是指您的 class 将另一个 class 的实例作为实例变量(有时称为字段)。

public class A {
    B otherObject;
    /* Other fields and methods go here */
}

在这种情况下,otherObject 只是对另一个类型 B 对象的实例的引用。otherObject 可以独立于 A 实例而存在,并且 A 的多个实例可以引用同一个 B。

内部 class 是指 class 定义实际上包含在外部 class 中。

public class C {
    class D {
        /* Inner class stuff goes here */
    }
}

这主要用于逻辑分组。在这种情况下,D 直接与 C 相关联,而 B 可能是也可能不是 A 的逻辑子级。在 C 之外访问 D 变得稍微复杂一些,但它只能通过 C 的现有实例访问。

So, by confronting the two definitions, i see some similarities: ... 3. can be declared private

你是对的,两者都可以声明为private,但是private 对这两者的意义是非常不同的。组合中使用的 private 意味着对该引用的访问仅限于 class。假设在您的执行代码中,您有一个类型为 A 的对象 A。您不能尝试访问 objectA.otherObject。 otherObject 只能从 A 的主体中引用。当您将内部 class 声明为 private 时,这意味着整个 class 的使用仅限于 A 的主体。您不能'在任何其他 class.

中的任何地方使用它

这两个概念是相关的。为了更好地组织我的想法,让我们定义 A 和 B:

  • A 是一个 class 成员,由一个内部 class.
  • 组成
  • B 是由外部 class.
  • 实例组成的 class 成员

示例:

class Driver {
}

class Car {

    // A
    class Engine {
        void start() {
            if (gasLevel > 0) {
                ...
            }
        }
    }

    //B
    Driver driver;

    int gasLevel;

}

也就是说:

  • A是一个字段
  • B 是一个字段
  • A 是一个内部 class
  • B不是内在class
  • A 可以访问汽车内部状态 (gasLevel)
  • B 无权访问汽车内部状态 (gasLevel)
  • 没有 Car 的实例,Engine 就不存在。
  • Driver 存在但没有 Car 的实例。

总而言之,两个不同 class 元素之间的组合和内部 class 的组合是控制系统耦合度和内聚度的方法。

阅读这篇关于作文的博客 post 似乎很容易理解.... Composition in JAVA