Model-View-Controller(MVC) 架構 (Architectural)設計模式

Trista's APP quest
5 min readJan 29, 2021

--

MVC之間的互動關係

Model 物件專責資料的封裝與相關的基礎行為。
View 物件代表使用者看得到的介面元件。
Controller 物件負責把 Model 物件與 View 物件連結在一起。

以 Controller 為核心去操控 View 與 Model 物件,並接收它們的通知。View 與 Model 物件之間不能直接溝通,要通過 Controller 才可以。

MVC中的 VC與views/controls和view controllers同義

views/controls和view controllers:
在 iOS 中用來構建用戶介面 (UI) 使用的所有物件。

views/controls:
包含UIView 類別、和其它提供用戶交互的 UI controls(UIKit 中的所有controls如 UIButton 和 UISlider,都繼承自 UIView類別),所以與 UIView 同義。

view controllers:
像 UIViewController、UITableViewController、UIPageViewController 等類別,這些類別使views/controls可用和實用。
A view controller’s main responsibilities include the following:

  • Updating the contents of the views, usually in response to changes to the underlying data.
  • Responding to user interactions with views.
  • Resizing views and managing the layout of the overall interface.
  • Coordinating with other objects — including other view controllers — in your app.

所以UIViewController蠻接近 UI-Delegate:既是 view 也是 controller。

MVC 雖然在理論上不錯,但在 iOS 和 Xcode 的背景下通常無法實現

因為view controllers在應用程式生命週期中扮演著與用戶互動的重要角色,所以開發人員將大部分應用程式的模型(數據)和業務邏輯程式碼放入view controllers。但是view controllers包含許多業務邏輯與 UI 組件混合的函式,將很難作測試。

Xcode 模板文件沒有包含表示 data model 的 class 或 struct。MVC 的 Model 部分似乎被假定了,而且幾乎有經驗的開發人員都視為理所當然。

Xcode 提供的 Interface Builder 編輯後最終的結果是個 XML 檔案,只有 layout 描述,沒有其他繪製或是更新資料到 UI 上的邏輯,於是將資料反映到 UI 上的 view 邏輯就變成 view controllers最主要的工作之一。

加上 @IBAction 只能接到 view controllers上, view controllers 會直接實作元件需要的 data source 和 delegate ,於是很多開發人員也就把 model 相關的邏輯放進來,這都導致 view controllers變肥大。

透過區分權責的思維模式,減低應用程式的複雜性

控制複雜性的重要條件,就是編寫小而邏輯集中組織的程式碼,像 Swift extension 語法結構等等。

為了解決 MVC 中肥大的 view controllers(Massive-View-Controller),Apple 開發圈引入了 MVVM 與 VIPER 等架構,意圖再把 Controller 拆分成職責更明確的角色。

編寫 Massive-View-Controller程式碼的陷阱,而不是真的在使用 MVC 架構設計模式

專案結構沒有Model 物件包含表示 data model 的 class 或 struct。

違反了關注點分離並導致程式碼膨脹,將在MVVM架構設計模式範例中看到一個很好的解決方案。

--

--

Trista's APP quest
Trista's APP quest

Written by Trista's APP quest

I believe ongoing endeavour to be a stronger self

No responses yet