如何在 Kotlin 中实现 Composition UML 关系?

How to implement in Kotlin the Composition UML relationship?

我有一个 UML 2.5 class diagram with a lot of composition relationships

我打算在 Kotlin 中实现它们(抱歉,我是 Kotlin 的新手):

class RuleScenarioState (val description : String){

    var action: RuleStateAction? = null

    var stateType : ScenarioStateType? = null

    var completeCriteria : StateCompleteCriteria? = null

    private class ComplexCompleteCriteria private constructor(val customCriteriaImplementation : String): StateCompleteCriteria()  {
    }

    private class ExpressionCompleteCriteria private constructor(val expression : RegulationExpression): StateCompleteCriteria() {
    }

    private class RegulationNodeCompleteCriteria   private constructor(val regulationNodeTreeId : UUID):  StateCompleteCriteria() {
    }

    private class CustomCompleteCriteria  private constructor(val customCriteriaImplementation : String): StateCompleteCriteria() {
    }

    private class CustomRuleStateAction private constructor(val customActionImplementationName : String): RuleStateAction() {
    }

    private class ClassificationRuleActionState  private constructor(val classificationExpression : RegulationExpression):  RuleStateAction() {
    }
}

不幸的是,我不知道如何使用这个 类,我只有一个需要实现的图表。我认为如上所示创建具有密集状态操作的实例是个坏主意,但如何确保一对一的实例关系?如何在Kotlin中正确实现UML组合关系?

UML 模型需要什么?

我也是 Kotlin 的新手。当你读到这种语言的组合时,你一定知道 object composition 和 UML 中的组合(也称为复合聚合。

UML 复合聚合是一种确保两件事的关联:

  • 组件实例(例如 RuleStateAction)由单个组合(例如 RuleScenarioState)独家拥有;
  • 复合体(例如RuleScenarioState)对其组件(例如RuleStateAction)的存在和存储负责,特别是如果复合体终止,其组件将被销毁.

如何在Kotlin中实现?

第一个要求意味着declare a private property to the class, using private var or private val. You should also make sure not to leak the object to the outside word by returning it in a way or in another. This can be a tricky point in some cases and may require to 对象。

第二个要求可以通过在组合中创建组件来实现。 Kotlin 是 , so if only the composite knows about the component, once the composite is no longer used, so is its component (you could also consider ,但我们不要增加不必要的困难 ;-)

几个不相关的评论:

  • 根据您的设计,您应该使用摘要 class 中的一些 abstract classes. You seem to have avoided them in your code, but they are essential for this design to work. So you'd have a private var that is initialized with an instance of a concrete class inherited

  • 你的图表没有说明组件的多样性。如果只有一个,则没有什么特别要添加的。但是如果很多,你就得考虑collections.