状态机图中的对象是什么?

What is an object in state machine diagram?

我正在尝试为我的 android 应用绘制状态机图。许多网站和书籍都说它显示了各种对象之间的转换。然而,由于缺乏UML知识,我无法理解对象的确切含义。

https://www.uml-diagrams.org/object.html中, 对象是 class.

的实例

那么对象是指代码中特定class的实例还是整个系统?我对此感到困惑。你能给我一个关于对象的例子吗?

UML 中的对象

一个对象在UML中定义如下:

A classifier describes a set of objects. An object is an individual with a state and relationships to other objects. The state of an object identifies the values for that object of properties of the classifier of the object.

但这很难理解:分类器的定义依赖于对象的概念,对象的定义依赖于分类器的概念。较短的“对象是 类 的实例”无助于解决这个先有鸡还是先有蛋的问题。

更难的是,这种查看对象的方式非常适合class based programming, but less the prototype-based programming

对象更务实

百本书已经讲过的,我就不去解释了。让我们来看看 Grady Booch 的定义(他是 UML 的创始人之一):

Object: Something you can do things to. An object has state, behavior, and identity; the structure and behavior of similar objects are defined in their common class. The terms instance and object are interchangeable.

更好的是,GoF 的定义非常幼稚但仍然非常有用:

An object packages both data and procedure that operates on that data.

“状态”是一个含糊不清的术语,在“对象状态”和“状态机状态”中使用时可能指的不是同一个现实。

对于对象来说,状态往往是指一个对象的所有数据。如果您保存和恢复一个对象的所有数据,您会期望它的操作会导致相同的结果和相同的行为。这通常是正确的,但并非总是如此。来自 Booch 的更准确的定义是:

The cumulative results of the behavior of an object; one of the possible conditions in which an object may exist (...)

状态机的状态具有略微不同的含义。状态不对应于单个对象状态,而是对应于一组可能的对象状态(单个对象的,或多个对象的,或整个系统的)。通常状态机状态以非常宽泛的术语描述底层集合。例如,状态可以描述对象或组件的生命周期或操作(创建、初始化、使用、存档、丢弃)中的一个阶段。

控制房间温度的状态机示例:

Named state (State machine)   Object state
TOO_COLD                      temp=12, min=16, max=19, power=1500
                              temp=13, min=16, max=19, power=1500
                              temp=15, min=16, max=19, power=900
RIGHT_TEMPERATURE             temp=16, min=16, max=19, power=100
                              temp=18, min=16, max=19, power=50                   
                              temp=19, min=16, max=19, power=50   
TOO_WARM                      temp=20, min=16, max=19, power=50
                              temp=21, min=16, max=19, power=0
                              temp=20, min=16, max=19, power=0
            

在此示例中,您可以看到状态机状态可以(并且大部分将)对应于一组(可能很大)对象状态。