因为任何实现接口(interface)的类都与所述接口(interface)的类型相同,所以与接口(interface)的任何关系是否也适用于实现它的任何东西?
例如,假设我们有一个名为 Product 的接口(interface),它有一个返回 Colour 类实例的方法签名。然后我们有 2 个类实现了这个接口(interface),称为 Shelf 和 Desk。这两个类包含类 Colour 的一个属性。
或者
关系是否只需要显示在 Product 和 Color 之间,还是 Product、Shelf 和 Desk 都需要显示它们与类 Colour 的关系?
最佳答案
接口(interface)的关联是否适用于它们的实现?
接口(interface)定义了一个契约,说明实现类必须提供的特性和它们必须满足的约束。如果一个接口(interface)与一个类 T 有关联,那么它的所有实现必须完全像它们也与一个类 T 有关联一样。
以下是 UML 规范告诉我们的内容:
Properties owned by Interfaces (including Association ends) imply that the realizing BehavioredClassifier should maintain information corresponding to the type and multiplicity of the Property and facilitate retrieval and modification of that information. A Property declared on an Interface does not necessarily imply that there will be such a Property on a realizing BehavioredClassifier (e.g., it may be realized by equivalent get and set Operations).
所以你的问题的答案是模棱两可的:
对于其中一种实现,您还可能遇到不同的情况,其中关联源自其他关联并且未明确维护。
你的叙述真的需要关联吗?
在您的叙述中,您证明需要关联是因为返回类型 T 的方法。但是具有参数或返回类型不足以要求关联,如 this other SO answer 中所述。 .关联需要 semantic relationship .
因此,您的界面更可能依赖于
Color
.杂项备注
在这两个图中,您应该用一个普通的空白箭头(末端的白色三角形)而不是一个开放的箭头末端来显示实现依赖关系。
在较旧的 UML 版本 1.xx 中,接口(interface)具有等同于抽象类的语义,并且不允许有自己的属性。虽然现在情况更加轻松,但我建议坚持使用这种方法,因为:
关于java - 在 UML 中,如果接口(interface)与类有关系,这种关系是否也适用于实现它的任何类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64866310/