網頁

2011/08/09

PureMVC重點整理

主要參考資料來源:
學習過程中感謝前輩們的資料,前人種樹、後人乘涼啊~以下為研究PureMVC時都會練習的Best Practices的重點整理,因為老是看了後面會忘記前面,是老了嗎...。

1.概念
  • MVC的代理分別為Proxy、Meditator、Command
    • Model<->Proxy
    • View<->Meditator
    • Controller<->Command
  • Facade and Core。
    • 單態模式Singleton。
    • 主要用來初始化MVC核心
    • 使Proxy、Meditator、Command可以互相拜訪
  • 使用Observer/Notification來實現內部溝通。
    • Facade 保存了Command與Notification間的映射。
    • 發送Notification->執行對應Command
    • Meditator發送、聲明、接收Notification
    • Facade、Proxy只能發送,但不接收Notification
2.Facade
  • Model、View、Controller三者的經紀人。主要訪問通知Proxy、Meditator、Command
  • Facade永不被實例化。應編寫成子類orwgn or 添加重寫Facade。
  • 除了頂層的Application,其它視圖不應該和Facde互動。
  • 使用。直接看Best Practices較清楚。
3.Notification
  • 實現觀察者模式。
  • 發送時可以帶一個「body」參數,可以是任何對向。
  • 另外可帶另一「type」參數,讓接收者作為識別的依據。
  • 可另外自已定義一個Notification。
  • 公用Notification常數名稱通常寫在Facade中。寫成常數避免打錯字的錯誤情況。
4.Command
流程:
  1. Controller 註冊監聽每一個Notification
  2. 事件發生通知
  3. Controller實例化Notification對應的Command
  4. Notification傳送參數給Command,並執行execute
重點:
  • 需要時才被創建,使用後即拋棄。(不要在生命周期長的物件中引用Command對象)
  • 用來協調Model與View
  • SimpleCommand執行單一命令。
  • MacroCommand執行多項命令。使用addCommand添加子Command。
  • 可以任意組合SimpleCommand、MacroCommand。
  • Model應封裝Domin logic、Command處理Business logic

5.Meditator
  • 主要處理View Component派發的事件和其它系統外發出的Notification訊息通知
  • 常將Proxy實例保存於屬性中,避免頻繁獲取Proxy實例。
  • 建構式提供兩個參數name和objec對象,object會將值給予viewComponent(protected)屬性。之後可以使用getter將object轉化成合適的型別。
  • 通常一個Meditator對應一個View Component,若其它包含多個子組件,請封裝Component對外的操作。
  • 接收事件後可能處理情況有:
    • 檢查類型或事件自定內容。
    • 檢查修改View Component屬性。
    • 檢查修改Proxy公布的屬性。
    • 發送一或多個Notifiction給Meditator or Command。
  • 實用小技巧
    • 多個Meditator對同一事件監聽,應發送一個Notification,不同的Meditator做各自的處理。
    • Meditator需要對其它Meditator作互動,最好的方法是用Command將步驟定義在一個地方。
    • 不應該讓一個Meditator去調用其它的Meditator。這是錯的!!
    • Proxy->更新狀態->Notification通知->Meditator反應到視圖。
  • 處理事件的方法:
    • Meditator初始化時會在listNotificationInterests方法中註冊感興趣的事的常數。
    • Meditator接收到感興趣的事件時,會叫用handleNotification方法。
    • 最好將所有的Notification處理方法放在handleNotification,並使用switch/case而不是if/else。
    • 處理的事件應在4、5個之內。太多則意味還Meditator還需要拆分。
    • View依賴Model、Model不應依賴View。
    • 使用Command、Notification來實現View與View的鬆偶合。
6.Proxy
主要用來管理程序數據模型,可能會有下列幾種類型:
  • Remote Proxy
  • Proxy and Delegate
  • Protection Proxy
  • Virtual Proxy
  • Smart Proxy
轉換數據對象
  • 建構式接受一個名稱name與object的參數,Object用來設置Proxy的數據模型,亦可始用setData設置
  • 使用getter將Data Object轉成真正的型別。
  • 不監聽Notification而是發送。
  • 將Domain Logic寫在Model,之後重構才不會使Model層引嚮到View或Controll。
  • 不應該引用、操作Meditator。

沒有留言: