Skip to main content

PureMVC 我也會 [5]

寫在前面...為日本地震海嘯受災戶祈福,為地球祈福...~_~



Proxy
  • 收集資料,提供公開方法给外部使用
  • 封裝資料區域邏輯(反正就是弄好資料才給別人)
  • 只能發送 Notification
  • 絕對不要引用到任何的 mediator,越自閉越好

Proxy 也是一個設計模式:Proxy design pattern,有興趣的請看 wiki 連結,以最簡單的解釋 Proxy 就是資料的「代理人」要什麼資料就是透過這個代理人取得,請求資料的對象不需要知道代理人是如何得到資料。

隨便畫個示意圖,MVC 中為什麼要分開 Model 用意就是當 Model 更改服務的時候,也只需要修改 Model。上圖中,如果你原本的服務是 PHP 會通過 ProxyA 去與後端溝通,當後端更改成 .NET 的時候,前面都不需要變動,也只需要更改為 ProxyB,在上一篇中有特別建議將 Proxy 取用寫在 Command 也是為了因應這種情況產生,這樣你只需要修改 proxyCommand 相關引用就可以了。

使用 Proxy 的時候通常都會伴隨 ValueObject 來使用,VO 的用意是為了強制資料型態,免得在開發過程中過度使用 Object 來做傳遞結果無法檢查資料型別而出現的 bug。

ValueObject

package com.mvc.models.vo
{
public class listVO
{
public function listVO(label:String, data:String){
this.label = label;
this.data = data;
}
public var label:String;
public var data:String;
}
}

當然你也可以使用 getter and setter 來定義屬性。

Value Object 好處是,使用 remoting 的時候可以直接與後端輸出物件型別綁定,前端收到後端吐出資料時,完全不需要做轉型,如:

package com.mvc.models.vo
{
[RemoteClass(alias='com.serverside.vo.listVO')]
public class listVO {
--以下省略--
}
}


以下是簡單的 Proxy 寫法:
兩個建議一定要覆寫的方法是:onRegister and onRemove
這隻 Proxy 作用只是當執行 getList() 時載入外部 xml,並發送清單資料

package com.mvc.models
{
import com.mvc.models.vo.listVO;

import mx.collections.ArrayCollection;
import mx.rpc.IResponder;

import org.puremvc.as3.patterns.proxy.Proxy;

public class ListProxy extends Proxy implements IResponder
{
public static const NAME:String = 'listProxy';
public static const LIST_CHANGED:String ="list_changed";

private var service : HTTPService;

public function ListProxy()
{
super(NAME, new ArrayCollection);
}
override public function onRegister():void
{
/*
* 通常建議要初始的東西寫在這邊,不要寫在 constructor 內
* Standard 版本感覺不出來有什麼差別
* Multi-code 版本就很容易有問題
*/
}
override public function onRemove():void
{
//移除 Proxy 後要做的事情
service = null;
}
public function getList():void{
if( service ){
sendNotification( LIST_CHANGED, list );
}else{
service = new HTTPService();
service.resultFormat = 'xml';
service.url = "data/list.xml";
service.send();
}
}
//隱藏的 getter 給自己看的,順便轉換資料型態
private function get list() : ArrayCollection {
return data as ArrayCollection;
}
/**
* Implemented mx.rpc.IResponder
*/
public function result( event:Object ):void{
var xml:XML = XML(event.result);
var list:ArrayCollection = new ArrayCollection;
for each (var subxml:XML in xml.list){
list.addItem( new listVO ( subxml.@name, subxml.@data));
}
setData(list);
//改完就要發 Notification
sendNotification( LIST_CHANGED, list );
}
public function fault( obj:Object ):void{
trace("XML 載入錯誤");
}
}
}

你會發現 基本上 Proxy 的 new 是帶有 proxyName:String, data:Object 兩個屬性,如果你的 Proxy 是唯一的,就使用 static var NAME:String 來註冊,如果 Proxy 是多個(如遊戲 room proxy)這時候的 public class ListProxy() 就需要改成:

public class ListProxy( proxyName:String ){
super( proxyName , new ArrayCollection);
}

這樣才可以建立多個 proxy instance。

通常一支 Proxy 並不會做這麼單一的事情,所以你可以將載入工作直接利用 Command or Delegate class 來執行

如:XMLServiceDelegate.as
要 load XML 的都透過這個就行了。

package com.mvc.models
{
import mx.rpc.AsyncToken;
import mx.rpc.IResponder;
import mx.rpc.http.HTTPService;

public class XMLServiceDelegate
{
public var responder : IResponder;
public var service : HTTPService;

public function XMLServiceDelegate( responder : IResponder, url:String)
{
// constructor will store a reference to the service we're going to call
this.service = new HTTPService();
this.service.resultFormat = 'xml';
this.service.url = url;

// and store a reference to the proxy that created this delegate
this.responder = responder;
}

public function load() : void
{
// call the service
var token:AsyncToken = service.send();
// notify this responder when the service call completes
token.addResponder( this.responder );
}
}
}


然後 ListProxy 修改成:

package com.mvc.models
{
import com.mvc.models.vo.listVO;

import mx.collections.ArrayCollection;
import mx.rpc.Responder;

import org.puremvc.as3.patterns.proxy.Proxy;

public class ListProxy extends Proxy
{
public static const NAME:String = 'listProxy';
public static const LIST1_CHANGED:String ="list1_changed";

private var list1:ArrayCollection;
//其他 list...這個 Proxy 用來儲存清單資料
private var list2:ArrayCollection;

public function ListProxy()
{
super(NAME, new ArrayCollection);
}
public function getList():void{
if( list1 ){
sendNotification( LIST1_CHANGED, list );
}else{
var delegate:XMLServiceDelegate = new XMLServiceDelegate(new Responder(list1Result, fault) , "data/list.xml");
delegate.load();
}
}

public function list1Result( event:Object ):void{
var xml:XML = XML(event.result);
list1 = new ArrayCollection;
for each (var subxml:XML in xml.list){
list1.addItem( new listVO ( subxml.@name, subxml.@data));
}
//改完就要發 Notification
sendNotification( LIST1_CHANGED, list1 );
}
public function fault( obj:Object ):void{
trace("XML 載入錯誤");
}
}
}

其實 Proxy 的玩法跟 Command 一樣很多,重點還是要練習才會有感覺...=)

Comments

  1. 感謝,在專案裏實在是太…好用了…van

    ReplyDelete

Post a Comment

Popular posts from this blog

[Swift3] weak 與 unowned 關鍵字

雖然在 Swift 中看起來"很像"是不需要煩惱內存管理的問題,不過實際上它還是遵循著自動引用計數 (ARC) 的規則,當一個物件沒有被其他對象引用時會自動被銷毀,如果三魂七魄沒有完全回位的話,就會有個靈體留在現世的空間裡,最經典的範例如下: 閉包(Closure)引用 classClassA { typealias Complete = ()->() var name : String var onComplete : Complete? init(_ name: String){ self.name = name print("Hello I am \(self.name)") onComplete = { print("\(self.name): onComplete!") // --> 閉包引用 self, 計數 + 1 } } deinit { print("deinit: \(self.name)") } } var a : ClassA? = ClassA("A") // --> 引用計數 + 1 a = nil // 2-1 = 1 還剩下 1 所以沒辦法銷毀 ---output------- Hello I am A 由於這邊的 onComplete 宣告為 Optional, 正確的做法要連同 onComplete 一起刪除才可以被回收,若不是 Optional 則會進入無法回收狀態: var b : ClassA? = ClassA("B") b?.onComplete = nil // --> 還好是 Optional 可以設成 nil 計數 - 1 b = nil // 計數 = 0 所以被回收 ---output------- Hello I am B deinit: B 但是做人不需要煩惱太多,這時候就出動 unowned 關鍵字讓物件可以順利被回收: onComplete = { [unowned self] in print...

[書評] 拖延心理學:為什麼我老是愛拖延?是與生俱來的壞習慣,還是身不由己?

作者: Jane B. Burka & Lenora M . Yuen 推薦指數 ★★★★★ 有時候,只是想了解事情發生原因而不是尋求解法 在這邊不是要講這本書的內容,而是想聊它對我的影響。