如何在 UML 中表示抽象 class 的子 class 应该是单例

How to represent in UML that subclasses of an abstract class should be singleton

假设一个抽象的 class X 及其子class 的 Y 和 Z。我如何在 UML class 图中表示 Y 和 Z 应该是单例。是否可以表示所有X子class必须是单例?

要指定 X 的所有子class 都是单例,可以在大括号之间写一个约束:{ X 的每个子class 都是单例}。此约束应放在 class 矩形中的约束隔间中。

UML 2.5 规范,§7.6.4 定义了一般约束的符号,§9.2.4 指定了如何显示 classifier 的约束:

If a Classifier owns Constraints, a conforming tool may implement a compartment to show the owned Constraints listed within a separate compartment of the owning Classifier’s rectangle. The name of this optional compartment is “constraints.”

或者,您可以在 X 的每个子 class 上给出单例指示。根据您的措辞,我认为这不是您想要的。无论如何,最新版本的 UML (2.5.1) 没有标准方法来指示 class 是单例。有些人通过在矩形的右上角写上 1 来表示它。但是,那不是有效的 UML。您可以将其用于零件,但不能用于 classes。相反,您可以发明自己的刻板印象 ≪单身 ≫。

There is another Whosebug question about this topic.

UML 2.5 规范的§11.4.4 说:

A usage dependency may relate an InstanceSpecification to a constructor for a Class, describing the single value returned by the constructor Operation. The Operation is the client, the created instance the supplier.

如果您创建一个具有 meta-property isComplete=true 的 GeneralizationSet(也就是说所有可能的子 class 都被考虑在内),并且您将一个 InstanceSpecification 连接到每个构造函数一个使用依赖性,该模型意味着每个 class 都是一个单例。

还有另一种可能性:您可以用 <<singleton>> 刻板印象来修饰 class。我总是那样使用它,编码器知道如何处理它。不是UML标准,但是看最后一句。