實體建築的架構常遵循特定風格(architectural style),例如維多利亞(Victorian)、美式工藝(American Craftsman)或裝飾藝術(Art Deco);每種風格是一組設計決策的總和,限制了建築的特徵與材料。軟體架構也有同樣的概念。
David Garlan 與 Mary Shaw 對架構風格的定義:
An architectural style defines a family of such systems in terms of a pattern of structural organization. More specifically, an architectural style determines the vocabulary of components and connectors that can be used in instances of that style, together with a set of constraints on how they can be combined. ——David Garlan and Mary Shaw,《An Introduction to Software Architecture》
換言之,架構風格提供一組有限的元素(component)與關係(connector),並對它們的組合方式加上限制。一個應用通常會混合使用多種風格。

Figure 3.15: An activity diagram showing a deployment pipeline with mixed automated and manual steps
分層架構(Layered Architecture)#
最經典的架構風格,把軟體元素分入不同的「層」。
- 每一層有清晰的責任。
- 強制依賴限制:每一層只能依賴正下方那一層(嚴格分層)或任何下方層。
- 可套用到上一節介紹的四個視角中任一個。
最常見的應用是「三層架構」(three-tier architecture),套用在領域視角:
- Presentation layer(表現層):實作 UI 或對外 API。
- Business logic layer(業務邏輯層):業務邏輯本體。
- Persistence layer(資料持久層):與資料庫互動。
分層架構的缺點#
分層架構雖是經典示範,但有幾個重大缺陷:
- 單一表現層:沒辦法表達「應用會被多種系統呼叫」的事實。
- 單一持久層:沒辦法表達「應用會與多種資料源互動」的事實。
- 業務邏輯層依賴持久層:理論上,這個依賴讓你無法在沒有資料庫的情況下測試業務邏輯。
分層架構也錯置了真實依賴關係。在設計良好的應用裡,業務邏輯通常定義 repository 介面,由 persistence tier 的 DAO 類別實作——換句話說,真實依賴方向與分層圖示反向。
六角架構(Hexagonal Architecture)#
六角架構是分層架構的替代方案。
- 業務邏輯位於核心(中間的六角形)。
- 不再有 presentation layer,而是用一個或多個 inbound adapter 接收外部請求並呼叫業務邏輯。
- 不再有 persistence tier,而是用一個或多個 outbound adapter 由業務邏輯呼叫,以存取外部應用。
- 關鍵特徵:業務邏輯不依賴介接卡;反過來,介接卡依賴業務邏輯。

Figure 3.16: An example of a hexagonal architecture — business logic at the center surrounded by adapters
Port 與 Adapter#
業務邏輯透過 port(連接埠)與外界互動。在 Java 裡,port 通常是 interface,分為兩類:
- inbound port:業務邏輯對外暴露的 API,讓外部應用可以呼叫。例如 service interface,定義服務的公開方法。
- outbound port:業務邏輯呼叫外部系統的方式。例如 repository interface,定義資料存取操作。
對應的 adapter 也分兩類:
- inbound adapter:處理外部請求,呼叫 inbound port。
- 範例:Spring MVC Controller(實作 REST endpoint 或 web 頁面)、message broker client(訂閱訊息)。
- 多個 inbound adapter 可呼叫同一個 inbound port。
- outbound adapter:實作 outbound port,從業務邏輯呼叫外部應用或服務。
- 範例:DAO 類別(存取資料庫)、proxy 類別(呼叫遠端服務);也可以發布事件。
六角架構的優點#
- 業務邏輯與 presentation/data access 解耦:業務邏輯不依賴於 presentation 邏輯或資料存取邏輯,可以單獨測試——測試時 mock outbound adapter,直接呼叫業務邏輯。
- 更貼近現代應用真實樣貌:業務邏輯可被多個 adapter 呼叫(REST、message、batch…),也可呼叫多個外部系統。
- 適合描述微服務裡每個服務的內部架構。
六角架構與分層架構都是架構風格——它們各自定義建構區塊與限制。本書後續章節會說明,巨石架構與微服務架構也是架構風格;兩者既可在領域視角搭配六角風格,也可在元件視角獨立分類。