Design Pattern (4) - UML (統一建模語言)

您可於此 design_pattern repo 下載 Design Pattern 系列程式碼。

UML (Unified Modeling Language)

UML 是一種用視覺圖形化來規劃建構軟體的方法。

不要急著寫程式,尤其是遇到較複雜的功能,先思考如何設計架構畫出 UML 圖,程式才會具有可讀性、維護性及擴展性。

Class 類別

如圖分為三列依序是

  1. Class 名稱
  2. Attribute 屬性
  3. Operations 方法

Interface 介面

Interface 有兩種表示法

一般表示法

一般型式與 Class 並無太大區別,只要在 Class Name 上方標註 <<interface>> 即可

棒棒糖表示法

用球狀來表示介面

Attribute 屬性

Visibility 可視範圍

Sign Modifiers
+ Public
# Protected
~ Package
- Private

Multiplicity 關聯多重性

Object 之間的數量關係,預設為 1

Sign amount
1 1 個
* 無限多個
n...m 至少 n 個,至多 m 個

Dependency 依賴

  • 表示不同對象之間相互依賴關係
  • 通常用於方法的參數或回傳值
  • A uses a B
  • 箭頭指向要依賴的對象
  • 虛線 + 箭頭 表示

動物使用(依賴)氧氣呼吸生存

Association 關聯

  • 表示一個對象擁有另一個對象
  • 通常用於屬性、全域變數
  • A has a C
  • Aggregation、Composition 為子集
  • 箭頭指向要關聯的對象
  • 實線 + 箭頭 表示

每個人有(關聯)一個地址

Aggregation 聚合

  • 表示一個對象擁有另一個對象
  • A owns a B
  • Association 為超集、Composition 為子集
  • 菱形指向要聚合的對象
  • 弱關聯,關聯及被關聯對象可互相獨立存在
  • 實線 + 空心菱形 表示

人擁有(聚合)衣服,人和衣服可以單獨存在

Composition 組合

  • 表示一個對象擁有另一個對象
  • C is a part of A
  • Association、Aggregation 為超集
  • 菱形指向要組合的對象
  • 強關聯,被關聯對象不可獨立存在
  • 實線 + 實心菱形 表示

人類有器官,人死了器官就無作用不存在了

(這邊先不討論器官可移植到別人身上的情況 😂 )

Association、Aggregation 及 Composition 三者關係

Aggregation and Composition are subsets of association meaning they are specific cases of association. In both aggregation and composition object of one class “owns” object of another class. But there is a subtle difference:

  • Aggregation implies a relationship where the child can exist independently of the parent. Example: Class (parent) and Student (child). Delete the Class and the Students still exist.
  • Composition implies a relationship where the child cannot exist independent of the parent. Example: House (parent) and Room (child). Rooms don’t exist separate to a House.

Realization / Implementation 實現 / 實作

  • 表示一個對象實作另一個對象
  • B implements A
  • 箭頭指向 interface
  • 虛線 + 空心箭頭 表示

心、肝、胃、腸要實作器官

Generalization / Inheritance 泛化 / 繼承

  • 表示一個對象繼承另一個對象
  • C is-a A
  • 箭頭指向 父類別
  • 實線 + 空心箭頭 表示

人是一種動物

總結

之後的 Design Pattern 系列文章會大量使用到 UML 圖,搞懂這些圖及箭頭的含義在軟體設計上是非常有幫助的,下一篇終於要進入第一個 Design Pattern。

參考

Note: 如果有任何建議、問題或不同想法,歡迎留言或寄信給我,可以一起討論進步成長 🙂




    Enjoy Reading This Article?

    Here are some more articles you might like to read next:

  • 💡 一台電腦操作多個 GitHub 帳號:最簡單快速的 SSH 設定方法
  • 🚀 如何使用 Excalidraw AI 快速生成專業級圖表,提升工作效率!
  • Setup Development Environment on a New macOS
  • Design Pattern (28) - Interpreter Pattern (解譯器模式)
  • Design Pattern (27) - Visitor Pattern (訪問者模式)