UML类图与序列图
技术讨论中,一个系统的结构通常只需类图+时序图的组合就可以表述清楚。
类图
**类图(Class Diagram)**包含系统中所有的类、接口,以及它们之间的相互关系,是系统结构的静态表示。
类图中的元素
- 类(Class)。包含类名、成员变量、成员函数三部分。

- 接口(Interface)。只有声明没有实现。

- 包(Package)。把功能关联的类/接口聚合到一起,增强可读性。

类图中类之间的关系
(双向)关联(Association): 当两个类以任意方式关联时。

- 有多重值的双向关联(Multiplicity): 表示出两个类之间的数量关系,一对多、多对多等等。

- 单向关联(Directed Association): 表示是单向关联。

- 自身关联(Reflexive Association): 类有多种身份,且类的一个实例与另一个实例相关。比如一个人既是经理也是职员。

聚合(Aggregation): 一个类是另一个类的组成部分。has a。

- 组合聚合(Composition): 被聚合的类的声明周期依赖于聚合类的生命周期。Company实例销毁时,Department实例也被销毁。

继承/泛化(Inheritance/Generalization): 继承/泛化关系。is a。

实例(Realization): 类实现接口。

时序图
**时序图(Sequence Diagram)**用于按照交互发生的一系列顺序,显示对象之间的这些交互。
时序图包含四类元素:
- 对象(Object)。
- 生命线(Lifeline)。
- 消息(Message)。
- 激活(Activation)。
示例
一个简单的情境:有一张订单,系统需要计算其价格。两种实现方式的时序图。后一种实现,即distributed control是比较好的程序实践。


一个应用了比较多种类符号的示例。

创建和删除元素

new消息之后立刻创建元素。删除元素用X表示,一个指向X的消息表示一个元素显式删除另一个元素,生命线最后一个X表示这个元素删除了自己。
循环、判断等等
表示这些概念需要交互框(Interaction frames)。
例如:
1 | procedure dispatch |

交互框左上角需要标明运算符,常见的有:
| Operator | Meaning |
|---|---|
| alt | Alternative multiple fragments; only the one whose condition is true will execute. |
| opt | Optional; the fragment executes only if the supplied condition is true. Equivalent to an alt with only one trace. |
| par | Parallel; each fragment is run in parallesl. |
| loop | Loop; the fragment may execute multiple times, and the guard indicates the basis of iteration. |
| region | Critical region; the fragment can have only one thread executing it at once. |
| neg | Negative; the fragment shows an invalid interaction. |
| ref | Reference; refers to an interaction defined on another diagram. The frame is drawn to cover the lifelines involved in the interaction. You can define parameters and a return value. |
| sd | Sequence diagram;used to surround an entire sequence diagram, if you wish. |
调用
**同步调用(Synchronous Message)**是只有当此调用执行完时才进行下一个。


**立即调用(Instantaneous Message)**是指从sender到receiver的时间可以忽略不计。如果需要时间很长的话,箭头不再水平。


Found Message是一个不知调用者是谁或者调用者是谁不重要的调用。

**异步调用(Asynchronous Message)**则不等待当前调用执行完,而是马上进行下一个。和同步调用在时序图上的区别是箭头。

**调用自身(Message to self)**应该少用,毕竟序列图是表示元素之间的关系的。

[1] http://www.developer.com/design/article.php/2206791/The-UML-Class-Diagram-Part-1.htm
[2] http://www.ibm.com/developerworks/cn/rational/rationaledge/content/feb05/bell/
[3] http://my.safaribooksonline.com/book/software-engineering-and-development/uml/0321193687/sequence-diagrams/ch04
[4] http://www.tracemodeler.com/articles/a_quick_introduction_to_uml_sequence_diagrams/